Ramón Wilhelm
Ramón Wilhelm

Reputation: 997

PyQt5: QMessageBox vanishes after starting

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

Upvotes: 1

Views: 2388

Answers (2)

DSchmidt
DSchmidt

Reputation: 1127

You can also connect it to your window if you want to show() it:

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() allows non-modal Dialogs: https://doc.qt.io/qt-5/qmessagebox.html#exec

Upvotes: 1

ekhumoro
ekhumoro

Reputation: 120768

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

Upvotes: 6

Related Questions