PyQt5: QMessageBox 启动后消失

PyQt5: QMessageBox vanishes after starting

当我调用错误消息一(参见代码中的注释)时,该消息快速出现然后消失。但是,如果我调用错误消息二,它会出现,并且只会在我单击 'OK' 按钮时消失。

如何修复它,使错误消息一像错误消息二一样工作?

    try:
        connection = pymysql.connect(host = 'localhost',
            user = 'root',
            db = 'Telephon Register',
            cursorclass = pymysql.cursors.DictCursor)  
        cur = connection.cursor()

        if number!= "":
            cur.execute("SELECT Number FROM formen WHERE Telephonebook = " + self.number.text() )
            result = cur.fetchone()

            if len(result) == 0:
                cur.execute("INSERT INTO formen VALUES(" + self.number.text())  
                connection.commit()
            else:
                print("The number " + number+ " already exists.")
        else:
            print("You have not typed a number!")
            msg = QMessageBox()  #EXCEPTION MESSAGE ONE
            msg.setIcon(2)
            msg.setText("Some Text")
            msg.setInformativeText("Some informative text")
            msg.setWindowTitle("Error")
            msg.show()

        connection.close()
    except:
        print("Connection does not work!")
        msg = QMessageBox()     # EXCEPTION MESSAGE TWO
        msg.setIcon(3)
        msg.setText("Some Text")
        msg.setInformativeText("Some message")
        msg.setWindowTitle("Error")
        msg.show()

消息框消失是因为您没有保留对它的引用,所以一旦函数 returns.

它就会被垃圾回收

要在您的示例中解决此问题,请使用 exec 打开消息框,以便它们阻塞直到用户关闭它们:

msg = QMessageBox()
...
msg.exec_() 

如果您想要 show(),您也可以将它连接到您的 window:

class Ui(QtWidgets.QMainWindow):

    def __init__(self, url, username, password, directory):
        super(Ui, self).__init__()
        uic.loadUi('dl.ui', self)
        [...]
        self.show()

        if directory:
            try:
                os.chdir(directory)
            except Exception as e:
                msg = QtWidgets.QMessageBox(self)
                msg.setIcon(QtWidgets.QMessageBox.Critical)
                msg.setWindowTitle("Error")
                msg.setText("Failed to change directory")
                msg.setInformativeText(f"this is bad")
                msg.show()

show() 允许非模态对话框: https://doc.qt.io/qt-5/qmessagebox.html#exec