PyQt5 closeEvent 方法
问题描述
我目前正在学习如何使用 pyqt5 构建应用程序,但遇到了 closeEvent 方法的一些问题,已被覆盖,因此 QMessageBox 对象要求用户确认.它似乎与 X 按钮配合得很好——当操作被确认时,事件被接受",当点击取消按钮时,事件被取消".但是,当我从下拉文件菜单中使用退出按钮时,无论我单击哪个按钮,程序都会以退出代码 1 关闭.看起来很奇怪,因为我在两种情况下都使用相同的 closeEvent 方法.
I'm currently learning how to build an application with pyqt5 and encountered some problem with closeEvent method, overriden so user gets asked for confirmation by QMessageBox object. It seems working well with X button - event gets 'accepted' when action is confirmed and 'canceled' when cancel button is clicked. However, when I use my Quit button from dropdown File menu, no matter which button I click, program gets closed with exit code 1. Seems strange, because I use same closeEvent method in both cases.
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_())
感谢您的建议!
解决方案
当您单击按钮时,程序会调用您的函数,但使用不同的 event
对象,该对象没有 accept()
和 ignore()
所以你会收到错误消息并且程序以退出代码 1 结束.
When you click button then program calls your function but with different event
object which doesn't have accept()
and ignore()
so you get error message and program ends with exit code 1.
您可以分配 self.close
并且程序将使用正确的事件对象调用 closeEvent()
.
You can assign self.close
and program will call closeEvent()
with correct event object.
quit.triggered.connect(self.close)
相关文章