PySide2:在不退出APP的情况下无法关闭QMessageBox

问题描述 投票:1回答:1

这里是一些小代码,其中有一个线程连接到ftp服务器并显示消息框。我不明白为什么msgBoxWait对话框关闭后,应用程序崩溃了(在FTP线程之前终止)。

我想这是因为它是最后显示的窗口,但是,添加QEventLoop并不能解决该问题。你能帮我吗?

# coding: utf-8

import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui


class Logic():
    def __init__(self):
        self.msgBoxWait = QtWidgets.QMessageBox()
        self.ftpThread = FtpThread()
        self.isConnected = False
        self.loop = QtCore.QEventLoop()

    def run(self):
        self.ftpThread.sigIsConnected.connect(self.ftpConnected, QtCore.Qt.QueuedConnection)
        self.ftpThread.finished.connect(self.ftpFinished, QtCore.Qt.QueuedConnection)
        self.ftpThread.sigError.connect(self.ftpError, QtCore.Qt.QueuedConnection)
        self.ftpThread.start()

        QtCore.QTimer.singleShot(200, self.showWaitMsgBox)

        self.loop.exec_()

    def showWaitMsgBox(self):
        self.msgBoxWait.setWindowTitle("Waiting")
        self.msgBoxWait.setText("""Waiting for ftp connection""")
        if not self.isConnected:
            self.msgBoxWait.exec()

    def ftpConnected(self):
        print("connected")
        self.isConnected = True
        self.msgBoxWait.close()  # <- crash here or when I click on the close button

    def ftpFinished(self):
        print("finished")
        self.ftpThread = None
        self.loop.quit()

    def ftpError(self, title, message):
        QtWidgets.QMessageBox.critical(None, title, message)


class FtpThread(QtCore.QThread):
    sigIsConnected = QtCore.Signal()
    sigError = QtCore.Signal(str, str)

    def run(self):
        QtCore.QThread.sleep(2)
        self.sigIsConnected.emit()
        QtCore.QThread.sleep(1)
        self.sigError.emit("error", "An error appened")
        QtCore.QThread.sleep(3)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    logic = Logic()
    QtCore.QTimer.singleShot(0, logic.run)

    sys.exit(app.exec_())
python qthread pyside2
1个回答
1
投票

默认情况下,Qt被配置为如果关闭了最后一个窗口,则应用程序将结束,因为通常这是预期的行为,但这不是您的情况,因为有时即使没有打开,也需要继续运行视窗。解决方案是将quitOnLastWindowClosed属性设置为False:

quitOnLastWindowClosed
© www.soinside.com 2019 - 2024. All rights reserved.