QComboBox

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
#include <QComboBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include <qapplication.h>

void setupComboBoxDemo(QWidget *parent) {
QVBoxLayout *layout = new QVBoxLayout(parent);

// --- 1. 基础下拉框 (只读模式) ---
QLabel *label1 = new QLabel("选择你的职业:", parent);
QComboBox *jobCombo = new QComboBox(parent);

// 添加选项
jobCombo->addItem("战士");
jobCombo->addItem("法师");
jobCombo->addItem("牧师");
// 也可以一次性添加
jobCombo->addItems({"刺客", "弓箭手"});

// --- 2. 可编辑下拉框 ---
QLabel *label2 = new QLabel("输入或选择城市(可自行输入):", parent);
QComboBox *cityCombo = new QComboBox(parent);
cityCombo->addItems({"北京", "上海", "广州"});
cityCombo->setEditable(true); // 开启编辑模式,用户可以自己打字
cityCombo->setPlaceholderText("请选择城市..."); // 只有在可编辑模式下有效

// --- 3. 实时显示结果的 Label ---
QLabel *displayLabel = new QLabel("当前选择:战士 (索引: 0)", parent);

// --- 4. 信号:currentIndexChanged ---
// 每当切换选项时触发。Qt 6 推荐使用 int 版本的信号
QObject::connect(jobCombo, &QComboBox::currentIndexChanged, [jobCombo, displayLabel](int index) {
QString text = jobCombo->currentText(); // 获取当前选中的文字
displayLabel->setText(QString("当前选择:%1 (索引: %2)").arg(text).arg(index));
});

// --- 5. 信号:currentTextChanged (针对可编辑模式) ---
QObject::connect(cityCombo, &QComboBox::currentTextChanged, [](const QString &text) {
qDebug() << "城市输入框内容变为:" << text;
});

layout->addWidget(label1);
layout->addWidget(jobCombo);
layout->addWidget(label2);
layout->addWidget(cityCombo);
layout->addWidget(displayLabel);
layout->addStretch();
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);

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

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

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