closeEvent和QMessageBox似乎阻止更新UI

时间:2013-12-23 08:36:21

标签: python pyside qmessagebox

我这个问题已经持续数小时了。我调查了很多东西(我甚至创建了一个自定义QDialog),但现在我确定它是closeEvent和QMessageBox组合导致了这个问题。我想知道的是,我是否有办法克服这个问题?

问题

我希望允许我的代码在关闭之前清理所有已使用的资源,如线程,DLL等。实际进行整个清理需要几秒钟的时间。为了向用户保证应用程序正常运行,我想'打印'状态消息,确认应用程序正在尝试清理其资源。

但是,使用下面的代码,我能得到的是“你确定.....”。 “Stopping App .....”消息未插入processEdit

我的代码段,test.py:

import sys, os, time
from PySide.QtGui import *
from PySide.QtCore import *
from time import sleep

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(350, 100, 300, 300)
        self.processEdit = QTextEdit()
        self.grid = QGridLayout()
        self.grid.addWidget(self.processEdit, 0, 0)
        self.setLayout(self.grid)
        self.show()

    def closeEvent(self, event = False):
        self.processEdit.insertHtml("\n\n Are you sure.....")
        if isinstance(event, QCloseEvent):
            event.ignore()
        confirm = QMessageBox.question(self, 'Message', "Are you sure you want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if confirm == QMessageBox.Yes:
            self.processEdit.insertHtml("\n\n Stopping App.....")

            # clean up resources and status reports here.
            time.sleep(5) # only here for the snippet

            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':

    qapp = QApplication(sys.argv)
    c = MainWindow()
    sys.exit(qapp.exec_())

1 个答案:

答案 0 :(得分:0)

正确插入了文字。但是,问题是您通过执行 closeEvent回调中的sleep / cleanup 来阻止事件循环。由于UI更新使用事件系统,因此在关闭应用程序之前不会处理下一个绘制事件。

在PyQt(没有PySide)中,我能够使用

来解决这个问题
self.processEdit.insertHtml("\n\n Stopping App.....")

event.accept()

self.repaint()
qapp.processEvents()

# clean up resources and status reports here.
time.sleep(5) # only here for the snippet

但我认为这是不好的做法(不仅仅是因为访问了一个全局变量)。即使在关机期间,您也应该尝试保持GUI响应。请参阅here