PyQt5 closeEvent 方法

时间:2023-03-12
本文介绍了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 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在 python 和 qml 中自动插入/编辑 QAbstractListModel 更新? 下一篇:在 QGraphicsView 中播放图像序列(神秘的内存泄漏)

相关文章