AlanHorman AlanHorman - 1 month ago 13
Python Question

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

Answer

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