4. QLineEdit输入框与文本回显

任务说明

本案例将使用 QLineEdit 构建一个最小可用的登录界面:包含用户名输入框、密码输入框(使用密码回显模式)以及登录按钮。点击登录按钮后,在界面下方以标签形式回显用户输入的用户名和密码内容。

实现思路

创建 QWidget 作为主窗口,使用 QFormLayout 排列标签与输入框,密码框通过 setEchoMode(QLineEdit::Password) 启用密码掩码。点击按钮时读取两个输入框的文本,拼接后显示在结果标签中。

完整代码

#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <QFormLayout>
#include <QVBoxLayout>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;
    window.setWindowTitle("登录界面");

    // 创建输入控件
    QLineEdit *usernameEdit = new QLineEdit();
    usernameEdit->setPlaceholderText("请输入用户名");

    QLineEdit *passwordEdit = new QLineEdit();
    passwordEdit->setPlaceholderText("请输入密码");
    passwordEdit->setEchoMode(QLineEdit::Password);  // 密码模式

    // 表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->addRow("用户名:", usernameEdit);
    formLayout->addRow("密码:", passwordEdit);

    // 按钮与结果标签
    QPushButton *loginBtn = new QPushButton("登录");
    QLabel *resultLabel = new QLabel();
    resultLabel->setWordWrap(true);

    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addLayout(formLayout);
    mainLayout->addWidget(loginBtn);
    mainLayout->addWidget(resultLabel);
    window.setLayout(mainLayout);

    // 点击登录后回显
    QObject::connect(loginBtn, &QPushButton::clicked, [&]() {
        QString username = usernameEdit->text();
        QString password = passwordEdit->text();
        resultLabel->setText(QString("用户名: %1\n密码: %2").arg(username, password));
    });

    window.resize(320, 160);
    window.show();

    return app.exec();
}

运行与验证

环境要求:Qt 5 或 Qt 6(Widgets 模块),支持 C++11 或更高版本。

编译运行:

qmake -project
qmake
make
./可执行文件名

或使用 CMake:

cmake_minimum_required(VERSION 3.16)
project(login_demo)
find_package(Qt6 REQUIRED COMPONENTS Widgets)
qt_standard_project_setup()
qt_add_executable(login_demo main.cpp)
target_link_libraries(login_demo Qt6::Widgets)

验证步骤:

  1. 在用户名输入框输入任意文本(如 testuser)。
  2. 在密码输入框输入任意文本(如 123456),观察输入内容显示为圆点掩码。
  3. 点击“登录”按钮,下方标签应显示:用户名: testuser 和 密码: 123456。
  4. 若密码框输入时显示为圆点而非明文,且点击按钮后回显内容与输入一致,则判定通过。

关键说明

  • setEchoMode(QLineEdit::Password) 是密码掩码的核心调用,若需同时显示掩码与明文切换,可改用 PasswordEdit 模式并配合复选框。
  • 回显密码仅为演示 text() 的读取方式,实际项目中不应明文回显密码。
  • 本案例未包含输入校验或空值判断,聚焦于 QLineEdit 的基本用法与信号槽连接。