《QT 108好類》之16 QComboBox類
- QT 108好類之16 QComboBox類
- QComboBox類特性和應用場景
- QComboBox類繼承關系
- QComboBox類使用
- 1 簡單使用
- 2 表單輸入
- 3 使用自定義模型和視圖
- 4 完全自定義彈出窗口
- QComboBox類類使用效果
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類使用
??常用方法:??
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)
{// 關鍵設置:必須設置窗口標志為 PopupsetWindowFlags(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);
}