PyQt5:QMessageBox在启动后消失

时间:2016-10-25 16:43:41

标签: python pyqt pyqt5 qmessagebox

当我调用错误消息一(请参阅代码中的注释)时,消息会快速显示然后消失。但是,如果我调用错误消息二,它会出现并且只有在我点击“确定”时才会消失。按钮。

如何修复它以便错误消息一像错误消息二一样?

    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()

1 个答案:

答案 0 :(得分:3)

消息框消失了,因为你没有保留对它的引用,所以一旦函数返回它就会被垃圾收集。

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

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