PyQt5 closeEvent方法 [英] PyQt5 closeEvent method
问题描述
我目前正在学习如何使用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)
这篇关于PyQt5 closeEvent方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!