from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(277, 244)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.actionQuit = QtWidgets.QAction(MainWindow)
self.actionQuit.setObjectName("actionQuit")
self.actionQuit.setShortcut("Ctrl+Q")
self.actionQuit.setStatusTip("Quit the application")
self.actionQuit.triggered.connect(MainWindow.closeEvent)
self.menuFile.addAction(self.actionQuit)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.show()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionQuit.setText(_translate("MainWindow", "Quit"))
class MyWindow(QtWidgets.QMainWindow):
def closeEvent(self, event):
print(event)
result = QtWidgets.QMessageBox.question(self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtWidgets.QMessageBox.Yes| QtWidgets.QMessageBox.No)
event.ignore()
print(result)
if result == QtWidgets.QMessageBox.Yes:
event.accept()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MyWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
sys.exit(app.exec_())
当我尝试使用Ctrl + Q快捷方式关闭应用程序时,会弹出MessageBox询问该问题,并且当我单击任一选项时都会得到
AttributeError: 'bool' object has no attribute 'ignore'
我在哪里错了?
答案 0 :(得分:2)
您不应该直接调用closeEvent()
方法(或xxxEvent
的方法),因为Qt的内部元素通过事件循环调用了此方法,而应该使用{{1} }方法来间接调用close()
:
closeEvent()
答案 1 :(得分:0)
通过将动作连接到类似功能的self.actionQuit.triggered.connect(MainWindow.closeEvent)
您确保将triggered
信号传递给函数,但是此信号是documentation中所写的布尔值,这意味着event
是下面代码中的布尔值:
def closeEvent(self, event):
print(event)
result = QtWidgets.QMessageBox.question(self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtWidgets.QMessageBox.Yes| QtWidgets.QMessageBox.No)
event.ignore()
print(result)
if result == QtWidgets.QMessageBox.Yes:
event.accept()
布尔值没有ignore
或accept
属性,因此没有AttributeError。我没有解决方案,但这是您问题的根源。希望通过键盘快捷键退出程序是一个已经解决的问题。