PyQt5: QMessageBox vanishes after starting

与世无争的帅哥 提交于 2019-12-20 07:27:05

问题


When I invoke Error Message One (see comments in code) the message quickly appears and then vanishes. But if I invoke Error Message Two, it appears and only vanishes when I click on the 'OK' button.

How can I fix it so that Error Message One works like Error Message Two?

    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:


The message-box disappears because you're not keeping a reference to it, so it gets garbage-collected as soon as the function returns.

To fix this in your example, open the message-boxes using exec, so that they block until the user closes them:

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


来源:https://stackoverflow.com/questions/40245405/pyqt5-qmessagebox-vanishes-after-starting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!