qt LineEdit

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <QApplication>
#include <QLineEdit>
#include <QLabel>
#include <QVBoxLayout>
#include <QDebug>


void setupLineEditDemo(QWidget *parent) {
// 创建一个垂直布局,让控件排好队
QVBoxLayout *layout = new QVBoxLayout(parent);

// --- 1. 基础输入框 ---
QLabel *label1 = new QLabel("普通输入框:", parent);
QLineEdit *editNormal = new QLineEdit(parent);
editNormal->setPlaceholderText("请输入用户名..."); // 占位符
editNormal->setMaxLength(10); // 限制长度

// --- 2. 密码输入框 ---
QLabel *label2 = new QLabel("密码输入框:", parent);
QLineEdit *editPassword = new QLineEdit(parent);
editPassword->setPlaceholderText("请输入密码...");
editPassword->setEchoMode(QLineEdit::Password); // 变成小圆点

// --- 3. 实时显示反馈的 Label ---
QLabel *displayLabel = new QLabel("你输入的内容将显示在这里", parent);
displayLabel->setStyleSheet("color: blue; font-weight: bold;");

// --- 4. 信号槽逻辑:实时监听文本变化 ---
// 只要输入框文字变了,displayLabel 就同步更新
QObject::connect(editNormal, &QLineEdit::textChanged, [displayLabel](const QString &text) {
if (text.isEmpty()) {
displayLabel->setText("你还没输入呢!");
} else {
displayLabel->setText("当前输入: " + text);
}
});

// --- 5. 信号槽逻辑:按回车键触发 ---
QObject::connect(editNormal, &QLineEdit::returnPressed, []() {
qDebug() << "用户在用户名框按了回车!";
});

// 将所有控件加入布局
layout->addWidget(label1);
layout->addWidget(editNormal);
layout->addWidget(label2);
layout->addWidget(editPassword);
layout->addWidget(displayLabel);
layout->addStretch(); // 弹簧:把内容顶到上方
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);

QWidget w;
w.setWindowTitle("QLineEdit 深度测试");
w.resize(400, 300);

// 调用我们的函数
setupLineEditDemo(&w);

w.show();
return a.exec();
}