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

Qt 5.15 C++ 登录对话框输错密码直接关闭无法重试问题

问题原因

现有代码中密码输入弹窗仅单次调用,密码校验失败分支里只有错误提示,没有重新触发输入弹窗的逻辑,提示弹出后代码直接执行到流程末尾,因此不会弹出重试输入框。

修改思路

用循环包裹密码输入、校验的全流程,只要密码校验不通过,就留在循环内重新弹出输入框;同时增加用户主动取消输入的判断、最大重试次数限制,避免出现死循环。

修改后代码
// 可自行调整最大密码错误重试次数
const int MAX_PASSWORD_RETRY = 5;
int passwordRetryCount = 0;
bool loginPass = false;

QString inputUser = QInputDialog::getText(nullptr, "Login", "username", QLineEdit::Normal);
if (inputUser == cnstnt::username)
{
    while (passwordRetryCount < MAX_PASSWORD_RETRY)
    {
        bool inputConfirmed = false;
        QString inputPwd = QInputDialog::getText(
            nullptr, 
            "Login", 
            "password", 
            QLineEdit::Password, 
            "", 
            &inputConfirmed
        );

        // 用户点击取消/关闭输入框时直接终止登录流程
        if (!inputConfirmed)
        {
            break;
        }

        QString hashedPwd = hlpr::passwordHash(inputPwd.toUtf8());
        if (hashedPwd == hlpr::getTxtPassword())
        {
            loginPass = true;
            w.show();
            break;
        }
        else
        {
            passwordRetryCount++;
            int leftChance = MAX_PASSWORD_RETRY - passwordRetryCount;
            if (leftChance > 0)
            {
                QMessageBox::warning(
                    nullptr, 
                    "error", 
                    QString("wrong password! remaining attempts: %1").arg(leftChance)
                );
            }
            else
            {
                QMessageBox::warning(nullptr, "error", "wrong password! no remaining attempts, login failed.");
            }
        }
    }
}
else
{
    QMessageBox::warning(nullptr, "error", "Kullanıcı adınız hatalı!");
}
补充说明
  • 如果不需要限制重试次数,可以去掉passwordRetryCount相关的判断,把循环条件改成while(true),只要用户不主动取消、不输对密码就一直弹输入框
  • 如果需要用户名输错时也支持重试,用同样的while循环包裹用户名输入、校验逻辑即可
  • QInputDialog::getText的最后一个参数用来接收用户的操作状态,点「确认」返回true,点「取消」/关闭弹窗返回false,必须加这个判断,否则用户点取消时会传入空字符串参与校验,导致无意义的循环弹框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:03:19