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);
QLabel *label1 = new QLabel("选择你的职业:", parent); QComboBox *jobCombo = new QComboBox(parent);
jobCombo->addItem("战士"); jobCombo->addItem("法师"); jobCombo->addItem("牧师"); jobCombo->addItems({"刺客", "弓箭手"});
QLabel *label2 = new QLabel("输入或选择城市(可自行输入):", parent); QComboBox *cityCombo = new QComboBox(parent); cityCombo->addItems({"北京", "上海", "广州"}); cityCombo->setEditable(true); cityCombo->setPlaceholderText("请选择城市...");
QLabel *displayLabel = new QLabel("当前选择:战士 (索引: 0)", parent);
QObject::connect(jobCombo, &QComboBox::currentIndexChanged, [jobCombo, displayLabel](int index) { QString text = jobCombo->currentText(); displayLabel->setText(QString("当前选择:%1 (索引: %2)").arg(text).arg(index)); });
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(); }
|