《QT 108好类》之16 QComboBox类

发布于:2025-09-11 ⋅ 阅读:(22) ⋅ 点赞:(0)

QT 108好类之16 QComboBox类

QComboBox是 常用的下拉框,它提供了一个下拉列表供用户选择选项。它结合了按钮和一个弹出的下拉列表(包含所有可选项)。

QComboBox类特性和应用场景

特性
1.​​项目存储:​​可以存储文本项 (QString)。可以存储图标项 (QIcon)。可以存储用户自定义数据 (QVariant),通过 setItemData()关联到每个项上。可以存储 QStandardItem对象(当使用模型/视图架构时)。

2.​​显示:​​显示当前选中的项(文本和/或图标)。点击按钮或使用键盘展开下拉列表显示所有选项。下拉列表可以是滚动列表),也可以是列表视图(需要自定义视图)。

3.​​可编辑性:​​默认是不可编辑的(用户只能从列表中选择)。可以通过 setEditable(true)设置为可编辑。此时:用户可以直接在行编辑区域输入文本。通常会启用自动补全 (setCompleter())。可以设置验证器 (setValidator()) 限制输入内容。当用户输入时,下拉列表会根据输入内容进行过滤(如果启用了)。

4.​​模型/视图支持:​​继承自 QAbstractItemView,因此支持模型/视图架构。可以使用 setModel()设置一个数据模型来管理其内容,实现更动态和复杂的数据展示。可以使用 setView()设置自定义视图来显示下拉列表,实现多列显示等高级效果。

应用场景
1.​​设置/配置对话框:​​选择语言、主题、单位制、分辨率、音质等级别等。选择连接端口、网络接口。选择文件格式、编码方式。
2.​​数据筛选/分类:​​在表格或列表上方,提供下拉菜单筛选特定类别(如“所有产品”、“电子产品”、“书籍”)。选择日期范围(如“今天”、“本周”、“本月”、“自定义”)。
3.​​表单输入:​​选择国家、省份、城市。选择性别、职业、教育程度等固定分类信息。选择产品型号、规格。
4.​​导航/视图切换:​​在标签页或工具栏中,提供下拉菜单切换不同的视图或工作区。
5.​​命令选择:​​提供一组命令或操作供用户选择(有时会配合工具栏按钮使用)。
6.​​动态内容加载:​​第一个下拉框选择大类(如“汽车品牌”),第二个下拉框根据第一个的选择动态加载小类(如该品牌下的“车型”)。
7.​​搜索/过滤(可编辑模式):​​用户可以直接输入文本进行搜索,下拉列表实时显示匹配项。

QComboBox类继承关系

QComboBox类继承自QWidget
QComboBox类继承关系

QComboBox类使用

​​常用方法:​​
addItem(const QString &text, const QVariant &userData = QVariant()): 添加一个文本项(可选附带用户数据)。
addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant()): 添加一个带图标的文本项。
insertItem(int index, …): 在指定索引处插入项。
removeItem(int index): 移除指定索引的项。
clear(): 移除所有项。
setCurrentIndex(int index): 设置当前选中的索引。
setCurrentText(const QString &text): 设置当前文本(在可编辑模式下直接设置文本;在不可编辑模式下,会查找匹配文本的项并选中)。
currentIndex(): 获取当前选中项的索引(如果没有选中项,返回 -1)。
currentText(): 获取当前选中项的文本(在可编辑模式下,返回行编辑框中的文本)。
currentData(int role = Qt::UserRole): 获取当前选中项关联的用户数据(默认 Qt::UserRole)。
itemText(int index): 获取指定索引项的文本。
itemData(int index, int role = Qt::UserRole): 获取指定索引项关联的用户数据。
count(): 获取项的数量。
setEditable(bool editable): 设置是否可编辑。
setModel(QAbstractItemModel *model): 设置数据模型。
setView(QAbstractItemView *itemView): 设置下拉列表使用的视图。
setCompleter(QCompleter *completer): 设置自动补全器(通常用于可编辑模式)。
setValidator(const QValidator *validator): 设置验证器(用于可编辑模式限制输入)。

信号:​​
currentIndexChanged(int index): 当前选中项的索引改变时触发(最常用)。
currentTextChanged(const QString &text): 当前选中项的文本改变时触发(在可编辑模式下,用户输入也会触发)。
activated(int index): 用户激活(选中)了一个项时触发(通常是通过鼠标点击或回车键确认选择)。
textActivated(const QString &text): 用户激活(选中)了一个项时触发,提供文本。
highlighted(int index): 用户在下拉列表中高亮(鼠标悬停或键盘导航)了一个项时触发。
editTextChanged(const QString &text): (仅在可编辑模式下)行编辑框中的文本改变时触发(用户输入时实时触发)。

1 简单使用

// 创建一个 QComboBox
QComboBox *comboBox = new QComboBox();
layout->addWidget(comboBox);

// 添加选项 (文本)
comboBox->addItem("Option 1");
comboBox->addItem("Option 2");
comboBox->addItem("Option 3");

// 添加带图标和用户数据的选项
comboBox->addItem(QIcon(":/images/logo.png"), "Favorite Option", QVariant(42));

// 插入一个选项到指定位置
comboBox->insertItem(1, "Inserted Option");

// 设置当前选中项 (索引从0开始)
comboBox->setCurrentIndex(2); // 选中 "Option 3"
// 连接信号:当选中项改变时
QObject::connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
                 [](int index) {
    qDebug() << "Current index changed to:" << index;
});

// 连接信号:当用户激活(选中)一个项时
QObject::connect(comboBox, QOverload<int>::of(&QComboBox::activated),
                 [comboBox](int index) {
    QString text = comboBox->itemText(index);
    QVariant data = comboBox->itemData(index);
    qDebug() << "Activated item: Index =" << index
             << "Text =" << text
             << "Data =" << data;
});

2 表单输入

// 创建标签
QLabel *countryLabel = new QLabel("国家:", this);
QLabel *provinceLabel = new QLabel("省份:", this);
QLabel *cityLabel = new QLabel("城市:", this);

// 创建组合框
QComboBox *countryCombo = new QComboBox(this);
QComboBox *provinceCombo = new QComboBox(this);
QComboBox *cityCombo = new QComboBox(this);

// 设置占位符文本
provinceCombo->addItem("-- 请选择省份 --");
cityCombo->addItem("-- 请选择城市 --");
QStringList countries;
countries<<"中国" << "美国" << "日本";
countryCombo->addItems(countries);
// 省份数据(按国家分组)
QMap<QString, QStringList> provinces;
provinces["中国"] = QStringList() << "北京" << "上海" << "广东" << "江苏" << "浙江";
provinces["美国"] = QStringList() << "加利福尼亚" << "德克萨斯" << "纽约" << "佛罗里达" << "伊利诺伊";
provinces["日本"] = QStringList() << "东京都" << "大阪府" << "北海道" << "爱知县" << "神奈川县";

// 城市数据(按省份分组)
QMap<QString, QStringList> cities;
cities["北京"] = QStringList() << "北京市";
cities["上海"] = QStringList() << "上海市";
cities["广东"] = QStringList() << "广州市" << "深圳市" << "东莞市" << "佛山市";
cities["江苏"] = QStringList() << "南京市" << "苏州市" << "无锡市" << "常州市";
cities["浙江"] = QStringList() << "杭州市" << "宁波市" << "温州市" << "嘉兴市";
cities["加利福尼亚"] = QStringList() << "洛杉矶" << "旧金山" << "圣何塞" << "圣地亚哥";
cities["德克萨斯"] = QStringList() << "休斯顿" << "达拉斯" << "奥斯汀" << "圣安东尼奥";
cities["纽约"] = QStringList() << "纽约市" << "布法罗" << "罗切斯特" << "扬克斯";
cities["东京都"] = QStringList() << "东京" << "新宿" << "涩谷" << "品川";
cities["大阪府"] = QStringList() << "大阪" << "堺市" << "高槻市" << "东大阪市";
cities["北海道"] = QStringList() << "札幌" << "函馆" << "旭川" << "小樽";

// 国家改变时更新省份
connect(countryCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
        this, [=](int index){
    if (index < 0) return;

    QString country = countryCombo->currentText();
    provinceCombo->clear();
    cityCombo->clear();

    if (provinces.contains(country)) {
        provinceCombo->addItem("-- 请选择省份 --");
        provinceCombo->addItems(provinces[country]);
    } else {
        provinceCombo->addItem("-- 无可用省份 --");
        cityCombo->addItem("-- 无可用城市 --");
    }
});

// 省份改变时更新城市
connect(provinceCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
        this, [=](int index){
    if (index <= 0) { // 0 是 "-- 请选择省份 --"
        cityCombo->clear();
        cityCombo->addItem("-- 请选择城市 --");
        return;
    }

    QString province = provinceCombo->currentText();
    cityCombo->clear();

    if (cities.contains(province)) {
        cityCombo->addItem("-- 请选择城市 --");
        cityCombo->addItems(cities[province]);
    } else {
        cityCombo->addItem("-- 无可用城市 --");
    }
});
QHBoxLayout *hlayout_2 =new QHBoxLayout;
layout->addLayout(hlayout_2);
hlayout_2->addWidget(countryLabel);
hlayout_2->addWidget(countryCombo);
hlayout_2->addWidget(provinceLabel);
hlayout_2->addWidget(provinceCombo);
hlayout_2->addWidget(cityLabel);
hlayout_2->addWidget(cityCombo);

3 使用自定义模型和视图

QComboBox *comboBox3 =new QComboBox(this);
CustomComboModel *model = new CustomComboModel;
model->appendRow(new QStandardItem("Important Item"));
model->appendRow(new QStandardItem("Normal Item"));
comboBox3->setModel(model);
// 创建自定义视图(带复选框)
QListView *listView = new QListView;
listView->setSelectionMode(QAbstractItemView::MultiSelection);
comboBox3->setView(listView);
// 多选处理
connect(comboBox3, QOverload<int>::of(&QComboBox::activated), [=](int index){
    QModelIndex modelIndex = comboBox3->model()->index(index, 0);
    Qt::CheckState state = static_cast<Qt::CheckState>(modelIndex.data(Qt::CheckStateRole).toInt());
    comboBox3->model()->setData(modelIndex,
                            state == Qt::Checked ? Qt::Unchecked : Qt::Checked,
                            Qt::CheckStateRole);
});
layout->addWidget(comboBox3);

class CustomComboModel : public QStandardItemModel
{
    Q_OBJECT
public:
    explicit CustomComboModel(QObject *parent = nullptr) : QStandardItemModel(parent) {}

    QVariant data(const QModelIndex &index, int role) const override {
        if (role == Qt::ForegroundRole && index.row() == 0) {
            return QColor(Qt::red); // 第一项显示为红色
        }
        return QStandardItemModel::data(index, role);
    }
};

4 完全自定义弹出窗口

CustomComboBox2 *Custom_ComboBox2 =new CustomComboBox2(this);
layout->addWidget(Custom_ComboBox2);

需要自己实现 showPopup()和hidePopup()

class CustomComboBox2 : public QComboBox {
    Q_OBJECT
public:
    CustomComboBox2(QWidget *parent = nullptr) : QComboBox(parent) {
        popup = new CustomComboPopup(this);
        connect(popup, &CustomComboPopup::selected, this, [this](const QString &text) {
            if (!text.isEmpty()) {
                qDebug()<<"selected text";
                clear();

                // 添加新的文本项

                addItem(text);

                // 设置当前索引为新添加的项(即第0项,因为clear后只添加了一项)

                setCurrentIndex(0);
                //setCurrentText(text);

            }
        });
    }

protected:
    void showPopup() override {
        //QPoint pos = mapToGlobal(QPoint(0, height()));
        //popup->move(pos);
        //popup->resize(width(), 150); // 设置弹出窗口大小

        // 计算弹出位置(在组合框下方)
        QPoint pos = mapToGlobal(QPoint(0, height()));

        // 移动弹出窗口到正确位置
        popup->move(pos);

        // 设置弹出窗口宽度与组合框相同,高度自适应
        popup->resize(width(), popup->sizeHint().height());

        popup->show();
    }
    void hidePopup() override {
        // 隐藏弹出窗口
        if (popup && popup->isVisible()) {
            popup->hide();
        }
    }

private:
    CustomComboPopup *popup;
};

class CustomComboPopup : public QWidget
{
    Q_OBJECT
public:
    explicit CustomComboPopup(QWidget *parent = nullptr);

signals:
    void selected(const QString &text);
};

CustomComboPopup::CustomComboPopup(QWidget *parent)
:QWidget(parent)
{
    // 关键设置:必须设置窗口标志为 Popup
    setWindowFlags(Qt::Popup);

    // 设置模态行为(可选,根据需求)
    setAttribute(Qt::WA_ShowWithoutActivating);

    QVBoxLayout *layout = new QVBoxLayout(this);

    QPushButton *btn1 = new QPushButton("Custom Button 1", this);
    QPushButton *btn2 = new QPushButton("Custom Button 2", this);
    QPushButton *btn3 = new QPushButton("Custom Button 3", this);

    layout->addWidget(btn1);
    layout->addWidget(btn2);
    layout->addWidget(btn3);

    connect(btn1, &QPushButton::clicked,this, [this]() {
        emit selected("Custom 1");
        hide();
    });
    connect(btn2, &QPushButton::clicked, [this]() { emit selected("Custom 2"); hide(); });
    connect(btn3, &QPushButton::clicked, [this]() { emit selected("Custom 3"); hide(); });

    setLayout(layout);

    // 设置合适的最小大小
    setMinimumSize(120, 100);
}

QComboBox类类使用效果

QComboBox类类使用效果


网站公告

今日签到

点亮在社区的每一天
去签到