PyQt5:启动后,QMessageBox消失了 [英] PyQt5: QMessageBox vanishes after starting

查看:740
本文介绍了PyQt5:启动后,QMessageBox消失了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用错误消息一(见代码注释)时,该消息迅速出现然后消失.但是,如果我调用错误消息二,则它会出现,并且仅在单击确定"按钮时消失.

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

推荐答案

消息框消失了,因为您没有保留对它的引用,因此该函数返回后将立即对其进行垃圾回收.

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

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

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

这篇关于PyQt5:启动后,QMessageBox消失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆