我正在学习这里的pyqt5教程Zetcode, PyQt5
作为一个练习,我试图在一个示例上展开,这样无论使用何种方法关闭应用程序,我都会看到相同的对话框消息框:单击标题栏中的“X”按钮(按预期工作)
单击“关闭”按钮(产生属性错误)
按“退出”键(有效,但不确定如何/为什么)
对话框在closeEvent方法中实现,最后提供完整的脚本。
我有两个问题:
1。单击“关闭”按钮时,我不想退出,而是要调用包含消息框对话框的closeEvent方法。
我已经替换了一行“关闭”按钮的示例代码:btn.clicked.connect(QCoreApplication.instance().quit)
而是尝试调用closeEvent方法,该方法已经实现了我想要的对话框:btn.clicked.connect(self.closeEvent)
但是,当我运行脚本并单击“关闭”按钮并在对话框中选择生成的“关闭”选项时,会得到以下结果:Traceback (most recent call last):
File "5-terminator.py", line 41, in closeEvent
event.accept()
AttributeError: 'bool' object has no attribute 'accept'
Aborted
有人能告诉我我做错了什么,需要在这里做什么吗?
2。当以某种方式按下escape键时,会显示消息框对话框,工作正常。
好的,它工作起来很好,但是我想知道CloseEvent方法中定义的消息框功能是如何以及为什么在keyPressEvent方法中调用的。
全文如下:import sys
from PyQt5.QtWidgets import (
QApplication, QWidget, QToolTip, QPushButton, QMessageBox)
from PyQt5.QtCore import QCoreApplication, Qt
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = QPushButton("Close", self)
btn.setToolTip("Close Application")
# btn.clicked.connect(QCoreApplication.instance().quit)
# instead of above button signal, try to call closeEvent method below
btn.clicked.connect(self.closeEvent)
btn.resize(btn.sizeHint())
btn.move(410, 118)
self.setGeometry(30, 450, 500, 150)
self.setWindowTitle("Terminator")
self.show()
def closeEvent(self, event):
"""Generate 'question' dialog on clicking 'X' button in title bar.
Reimplement the closeEvent() event handler to include a 'Question'
dialog with options on how to proceed - Save, Close, Cancel buttons
"""
reply = QMessageBox.question(
self, "Message",
"Are you sure you want to quit? Any unsaved work will be lost.",
QMessageBox.Save | QMessageBox.Close | QMessageBox.Cancel,
QMessageBox.Save)
if reply == QMessageBox.Close:
event.accept()
else:
event.ignore()
def keyPressEvent(self, event):
"""Close application from escape key.
results in QMessageBox dialog from closeEvent, good but how/why?
"""
if event.key() == Qt.Key_Escape:
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())
希望有人能花点时间来启发我。