【发布时间】:2016-11-16 00:25:15
【问题描述】:
我目前正在学习如何使用 pyqt5 构建应用程序,但遇到了 closeEvent 方法的一些问题,已被覆盖,因此 QMessageBox 对象要求用户确认。它似乎与 X 按钮配合得很好——当操作被确认时,事件被“接受”,当点击取消按钮时,事件被“取消”。但是,当我从下拉文件菜单中使用退出按钮时,无论我单击哪个按钮,程序都会以退出代码 1 关闭。看起来很奇怪,因为我在两种情况下都使用相同的 closeEvent 方法。
import sys
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QAction
class window(QMainWindow):
def __init__(self):
super().__init__()
def createUI(self):
self.setGeometry(500, 300, 700, 700)
self.setWindowTitle("window")
quit = QAction("Quit", self)
quit.triggered.connect(self.closeEvent)
menubar = self.menuBar()
fmenu = menubar.addMenu("File")
fmenu.addAction(quit)
def closeEvent(self, event):
close = QMessageBox()
close.setText("You sure?")
close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
close = close.exec()
if close == QMessageBox.Yes:
event.accept()
else:
event.ignore()
main = QApplication(sys.argv)
window = window()
window.createUI()
window.show()
sys.exit(main.exec_())
感谢您的建议!
【问题讨论】:
-
你是在控制台/终端中运行的吗?你有错误信息。
AttributeError: 'bool' object has no attribute 'accept' -
当您单击按钮然后系统调用您的函数,但使用不同的
event对象,该对象没有accept()和ignore(),因此您会收到错误消息并且程序以退出代码 1 结束。