我已经收到这个问题几个小时了。我调查了很多事情(我什至创建了一个自定义 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_())