PyQt5 closeEvent method(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)
这篇关于PyQt5 closeEvent 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PyQt5 closeEvent 方法


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01