1

我已经收到这个问题几个小时了。我调查了很多事情(我什至创建了一个自定义 QDialog),但现在我确定是 closeEvent 和 QMessageBox 组合导致了这个问题。我想知道是否有任何方法可以让我克服这个问题?

问题

我想让我的代码在关闭之前清理所有使用的资源,例如线程、DLL 等。实际完成整个清理工作需要几秒钟。为了用户保证应用程序运行正常,我想“打印”一条状态消息,确认应用程序正在尝试清理其资源。

但是,使用下面的代码,我只能得到“你确定......”。“正在停止应用程序.....”消息未插入到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_())
4

1 回答 1

0

文本已正确插入。但是,问题在于您通过在 closeEvent 回调中执行睡眠/清理来阻止事件循环。由于 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 响应,即使在关机期间也是如此。见这里

于 2013-12-23T09:19:21.590 回答