You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询PyQt中登录成功后通过QMessageBox打开新窗口的简便方法

解决方案

1. 移除多余的pushButton2控件

删掉UI代码中与pushButton2相关的所有内容,无需保留这个中间按钮:

# 仅保留登录按钮的代码
self.pushButton = QPushButton(self.verticalWidget)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.clicked.connect(self.login)
self.verticalLayout_2.addWidget(self.pushButton)

2. 修改login函数的成功分支逻辑

利用QMessageBox的模态特性,在用户点击成功消息框的确认按钮后,直接调用主窗口打开函数:

def login(self):
    email = self.emailLineEdit.text().strip()
    password = self.passwordLineEdit.text().strip()
    # 修正空值判断逻辑,原逻辑存在判断失效问题
    if email and password:
        # 改用参数化查询,避免SQL注入风险
        mydb = mc.connect(
            host="localhost",
            user="root",
            password=os.getenv('mysqlpass'),
            database="cinedeck")

        mycursor = mydb.cursor()
        query = "SELECT email, password FROM user_info WHERE email = %s"
        mycursor.execute(query, (email,))
        result = mycursor.fetchone()
        mydb.close()
        
        if result:
            if result[1] == password:
                QMessageBox.about(self, "Success ✅", "Successfully logged into Cinedeck!")
                # 消息框关闭后立即打开主窗口
                self.openhomescreen()
            else:
                QMessageBox.about(self, "Error ⚠️", "Incorrect Password!")
        else:
            QMessageBox.about(self, "Error ⚠️", "Account does not exist!")
    else:
        QMessageBox.about(self, "Error ", "Please Enter Email and Password.")

def openhomescreen(self):
    self.selfhomewindow.setupUi(self)
    # 可选:如果主窗口未自动显示,添加该行确保窗口展示
    # self.show()

关键说明

  • 修复空值判断:原代码中password is not None永远为真(QLineEdit.text()返回字符串类型),改用if email and password可准确判断输入不为空。
  • 安全优化:将SQL查询改为参数化形式,避免直接拼接字符串导致的SQL注入漏洞。
  • 模态对话框特性:QMessageBox.about会阻塞线程直到用户点击确认按钮,因此后续的主窗口打开代码会在用户操作后立即执行,完全符合需求。

内容的提问来源于stack exchange,提问作者Koshy John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:40:15