Qt开发:QComboBox的使用
文章目录
- 一、概述
- 二、QComboBox添加数据
- 三、常用函数
- 四、信号与槽函数
一、概述
QComboBox 是 Qt 提供的一个下拉列表控件,它允许用户从预定义的选项中进行选择,同时也支持手动输入自定义内容(如果启用了可编辑模式)。QComboBox 继承自 QWidget,并提供了丰富的 API 用于管理选项、响应用户交互等。
二、QComboBox添加数据
void addItem(const QString &text, const QVariant &userData = QVariant())
void addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
void addItems(const QStringList &texts)
在 Qt 中,QComboBox 提供了 addItem 和 addItems 三个重载函数,用于向下拉列表中添加选项。
这些函数支持:
- 仅添加文本选项。
- 添加带有 QIcon 图标的选项。
- 批量添加多个文本选项。
1.addItem(const QString &text, const QVariant &userData = QVariant())
该函数向 QComboBox 中添加一个选项,文本内容由 text 指定,同时可以绑定一个额外的 QVariant 数据(可选)。
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox();comboBox->addItem("苹果", 100); // 绑定整数数据comboBox->addItem("香蕉", "yellow"); // 绑定字符串数据comboBox->addItem("橙子"); // 仅添加文本,不绑定数据// 获取选中项的文本和数据QString selectedText = comboBox->currentText();QVariant selectedData = comboBox->currentData();qDebug() << "选中的文本:" << selectedText;qDebug() << "选中的数据:" << selectedData.toInt();
}
输出结果:
2. addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
该函数不仅可以添加文本,还可以为选项设置一个 QIcon 图标,同时支持绑定 QVariant 数据(可选)。
QComboBox *comboBox = new QComboBox();
comboBox->addItem(QIcon(":/icons/apple.png"), "苹果", 100);
comboBox->addItem(QIcon(":/icons/banana.png"), "香蕉", "yellow");
comboBox->addItem(QIcon(":/icons/orange.png"), "橙子");qDebug() << "当前选中的文本:" << comboBox->currentText();
qDebug() << "当前选中的数据:" << comboBox->currentData().toInt();
3. addItems(const QStringList &texts)
该函数用于批量添加多个文本选项。
QStringList fruits = {"苹果", "香蕉", "橙子", "葡萄"};
comboBox->addItems(fruits);
void insertItem(int index, const QString &text, const QVariant &userData = QVariant())
void insertItem(int index, const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
void insertItems(int index, const QStringList &list)
1. void insertItem(int index, const QString &text, const QVariant &userData = QVariant())
作用: 在指定 index 位置插入一个文本项,并可选地附加 userData(用户自定义数据)。
参数:
- index:插入位置的索引(如果 index 超出范围,则插入到末尾)。
- text:插入项的显示文本。
- userData(可选):存储附加数据(如 ID、数据库键值等)。
QComboBox comboBox;
comboBox.addItem("Apple");
comboBox.addItem("Banana");// 在索引 1 处插入 "Cherry",并附加 ID 303
comboBox.insertItem(1, "Cherry", 303);// 结果:
// Index 0 -> "Apple"
// Index 1 -> "Cherry"
// Index 2 -> "Banana"
2. void insertItem(int index, const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
作用: 在指定 index 位置插入一个带图标的文本项,并可选地附加 userData(用户自定义数据)。
参数:
- index:插入位置的索引(如果超出范围,则插入到末尾)。
- icon:图标(QIcon)。
- text:插入项的显示文本。
- userData(可选):存储附加数据。
QComboBox comboBox;
QIcon appleIcon(":/icons/apple.png");
QIcon bananaIcon(":/icons/banana.png");comboBox.insertItem(0, appleIcon, "Apple", 101);
comboBox.insertItem(1, bananaIcon, "Banana", 202);// 结果:
// Index 0 -> "Apple" (带 appleIcon)
// Index 1 -> "Banana"(带 bananaIcon)
3. void insertItems(int index, const QStringList &list)
作用: 在指定 index 位置批量插入多个文本项。
参数:
- index:插入位置的索引(如果 index 超出范围,则插入到末尾)。
- list:要插入的文本项列表(QStringList)。
QComboBox comboBox;
comboBox.addItem("Apple");// 在索引 1 处批量插入多个选项
QStringList fruits = {"Banana", "Cherry", "Grapes"};
comboBox.insertItems(1, fruits);// 结果:
// Index 0 -> "Apple"
// Index 1 -> "Banana"
// Index 2 -> "Cherry"
// Index 3 -> "Grapes"
void setItemData(int index, const QVariant &value, int role = Qt::UserRole)
void setItemIcon(int index, const QIcon &icon)
void setItemText(int index, const QString &text)
void setLineEdit(QLineEdit *edit)
1. void setItemData(int index, const QVariant &value, int role = Qt::UserRole)
作用:设置 QComboBox 指定索引 (index) 处的 附加数据,存储在 role 指定的角色中。
参数:
- index:要修改的项的索引(从 0 开始)。
- value:要存储的数据,类型为 QVariant。
- role(默认值 Qt::UserRole):数据的类型,可以是 Qt::ItemDataRole 枚举值,例如:Qt::UserRole(默认,用户自定义数据)、Qt::DecorationRole(存储图标)、Qt::ToolTipRole(存储鼠标悬停时的提示文本)。
QComboBox *comboBox = new QComboBox(this);comboBox->addItem("Apple");comboBox->setItemData(0, 101, Qt::UserRole); // 为第 0 项存储一个 IDcomboBox->setItemData(0, "This is an apple", Qt::ToolTipRole); // 设置鼠标提示// 存储图标//QPixmap iconPixmap(":/icons/sample.png");//comboBox->setItemData(0, iconPixmap, Qt::DecorationRole);//QVariant iconData = comboBox->itemData(0, Qt::DecorationRole);
2.void setItemIcon(int index, const QIcon &icon)
作用:为 QComboBox 指定索引 (index) 处的项 设置图标。
参数:
- index:要修改的项的索引。
- icon:要设置的 QIcon。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Folder");
comboBox->setItemIcon(0, QIcon(":/icons/folder.png")); // 为第 0 项设置图标
3. void setItemText(int index, const QString &text)
作用:修改 QComboBox 指定索引 (index) 处的项的 文本。
参数:
- index:要修改的项的索引。
- text:新的文本。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Old Name");
comboBox->setItemText(0, "New Name"); // 修改第 0 项的文本
4. void setLineEdit(QLineEdit *edit)
作用:设置 QComboBox 内部的 QLineEdit,用于 自定义输入框(当 QComboBox::setEditable(true) 时生效)。
参数:
edit:QLineEdit 对象的指针。
QLineEdit *customEdit = new QLineEdit();
customEdit->setPlaceholderText("Enter item...");
customEdit->setStyleSheet("color: blue; font-weight: bold;");QComboBox *comboBox = new QComboBox(this);
comboBox->setEditable(true);
comboBox->setLineEdit(customEdit); // 替换默认输入框
三、常用函数
1. QCompleter completer() const
功能:获取 QComboBox 当前使用的 QCompleter(如果有)。QCompleter 用于提供自动补全功能。
#include <QComboBox>
#include <QCompleter>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);comboBox->setGeometry(100, 100, 250, 40);QStringList words = {"苹果", "香蕉", "橙子", "草莓", "葡萄"};QCompleter *completer = new QCompleter(words);comboBox->setCompleter(completer);comboBox->setEditable(true);comboBox->addItems(words);
}
2. int count() const
功能:返回 QComboBox 中选项的总数。
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);QStringList words = {"苹果", "香蕉", "橙子", "草莓", "葡萄"};comboBox->addItems(words);qDebug() << "QComboBox 选项总数:" << comboBox->count();
}
3. QVariant currentData(int role = Qt::UserRole) const
功能:获取当前选中项的 QVariant 绑定数据,默认为 Qt::UserRole。
comboBox->addItem("苹果", 100);
comboBox->addItem("香蕉", 200);QVariant data = comboBox->currentData();
qDebug() << "当前选项的数据:" << data.toInt();
4. int currentIndex() const
功能:获取 QComboBox 当前选中项的索引。
qDebug() << "当前选中项索引:" << comboBox->currentIndex();
5. QString currentText() const
功能:获取 QComboBox 当前选中项的文本内容。
qDebug() << "当前选中项文本:" << comboBox->currentText();
6.bool duplicatesEnabled() const
功能:检查当前 QComboBox 是否允许重复的条目(item)。
返回值:
- true:允许重复项,即 QComboBox 可以包含多个相同的条目。
- false:不允许重复项,添加相同的条目时不会插入。
默认值: false(即默认不允许重复项)。
相关函数:void setDuplicatesEnabled(bool enable): 设置是否允许重复条目。
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 默认不允许重复项qDebug() << "Before setting: " << comboBox->duplicatesEnabled(); // false// 允许重复项comboBox->setDuplicatesEnabled(true);qDebug() << "After setting: " << comboBox->duplicatesEnabled(); // true// 添加条目comboBox->addItem("Apple");comboBox->addItem("Banana");comboBox->addItem("Apple"); // 允许重复,成功添加
}
8.int findData(const QVariant &data, int role = Qt::UserRole, Qt::MatchFlags flags = Qt::MatchExactly) const
功能:在 QComboBox 的 item 数据中查找匹配的项,并返回其索引(index)。如果找不到匹配项,则返回 -1。
参数说明:
data(const QVariant &):要查找的数据值,它可以是 QString、int、QVariant 等类型。
role(int,默认 Qt::UserRole):
- 指定查找的 数据角色(Data Role)。
- 默认值是 Qt::UserRole,表示匹配的是 setItemData(index, value, Qt::UserRole) 存储的数据。Qt::DisplayRole:匹配 文本(text)(即 addItem(text) 的值)。
- flags(Qt::MatchFlags,默认 Qt::MatchExactly)指定 匹配模式:Qt::MatchExactly(默认):完全匹配。Qt::MatchContains:包含匹配(部分匹配)。Qt::MatchStartsWith:前缀匹配。Qt::MatchEndsWith:后缀匹配。
返回值:
- 找到匹配项时,返回该项的索引(index)。
- 未找到匹配项时,返回 -1。
** 按文本查找(默认 Qt::DisplayRole)**
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 添加选项comboBox->addItem("Apple");comboBox->addItem("Banana");comboBox->addItem("Cherry");// 查找文本 "Banana"int index = comboBox->findData("Banana", Qt::DisplayRole);qDebug() << "Index of 'Banana':" << index; // 输出 1(索引从0开始)// 查找不存在的文本int notFound = comboBox->findData("Orange", Qt::DisplayRole);qDebug() << "Index of 'Orange':" << notFound; // 输出 -1(未找到)
}
按 Qt::UserRole 自定义数据查找
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 添加选项,并给每个项存储一个 ID 作为 UserRole 数据comboBox->addItem("Apple", 101); // UserRole = 101comboBox->addItem("Banana", 202); // UserRole = 202comboBox->addItem("Cherry", 303); // UserRole = 303// 查找 UserRole = 202 对应的索引int index = comboBox->findData(202, Qt::UserRole);qDebug() << "Index of item with UserRole 202:" << index; // 输出 1// 查找不存在的 UserRole 数据int notFound = comboBox->findData(999, Qt::UserRole);qDebug() << "Index of item with UserRole 999:" << notFound; // 输出 -1
}
使用 Qt::MatchContains 进行模糊查找
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);/// 添加选项comboBox->addItem("Apple");comboBox->addItem("Green Apple");comboBox->addItem("Banana");// 使用部分匹配(包含 "Apple")int index = comboBox->findData("Apple", Qt::DisplayRole, Qt::MatchContains);qDebug() << "First match for 'Apple' (MatchContains):" << index; // 可能返回 0 或 1
}
9.int findText(const QString &text, Qt::MatchFlags flags = …) const
功能:在 QComboBox 的选项文本(text)中查找匹配项,并返回其索引(index)。如果找不到匹配项,则返回 -1。
参数说明:
text(const QString &):要查找的字符串(即 QComboBox 选项的显示文本)。
flags(Qt::MatchFlags,默认 Qt::MatchExactly)指定查找模式:
- Qt::MatchExactly(默认):完全匹配。
- Qt::MatchContains:包含匹配(部分匹配)。
- Qt::MatchStartsWith:前缀匹配(以 text 开头)。
- Qt::MatchEndsWith:后缀匹配(以 text 结尾)。
- Qt::MatchCaseSensitive:区分大小写匹配(可与其他匹配模式组合使用)。
返回值:
- 找到匹配项时,返回该项的索引(index)。
- 未找到匹配项时,返回 -1。
精确匹配(默认 Qt::MatchExactly)
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 添加选项comboBox->addItem("Apple");comboBox->addItem("Banana");comboBox->addItem("Cherry");// 精确查找 "Banana"int index = comboBox->findText("Banana");qDebug() << "Index of 'Banana':" << index; // 输出 1// 查找不存在的文本int notFound = comboBox->findText("Orange");qDebug() << "Index of 'Orange':" << notFound; // 输出 -1
}
使用 Qt::MatchContains 进行模糊查找
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 添加选项comboBox->addItem("Apple");comboBox->addItem("Banana");comboBox->addItem("Cherry");// 使用部分匹配(包含 "Apple")int index = comboBox->findText("App", Qt::MatchContains);qDebug() << "First match for 'Apple' (MatchContains):" << index; // 可能返回 0 或 1
}
前缀匹配(Qt::MatchStartsWith)
int index = comboBox.findText("Gre", Qt::MatchStartsWith);
qDebug() << "Index of first item starting with 'Gre':" << index; // 可能返回 1
后缀匹配(Qt::MatchEndsWith)
int index = comboBox.findText("ana", Qt::MatchEndsWith);
qDebug() << "Index of first item ending with 'ana':" << index; // 可能返回 2(Banana)
区分大小写匹配(Qt::MatchCaseSensitive)
int index = comboBox.findText("apple", Qt::MatchExactly | Qt::MatchCaseSensitive);
qDebug() << "Index of case-sensitive 'apple':" << index; // -1,因为 "Apple" 是大写
10.QVariant itemData(int index, int role = Qt::UserRole) const
功能:该函数返回 QVariant,表示 QComboBox 中某个索引项的特定角色 (role) 对应的数据。
参数说明:
index:要查询的项目索引(从 0 开始)。
role(默认值 Qt::UserRole):要获取的数据的角色,常见角色包括:
- Qt::DisplayRole(默认显示文本)
- Qt::UserRole(用户自定义数据)
- Qt::DecorationRole(图标)
- 其他 Qt::ItemDataRole 枚举值
返回值:
- 返回存储在 index 处 role 角色的数据,以 QVariant 形式存储。
- 如果索引无效,则返回 空的 QVariant。
#include <QComboBox>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);// 添加选项,并存储额外的 ID 数据comboBox->addItem("Apple", 101);comboBox->addItem("Banana", 102);comboBox->addItem("Cherry", 103);// 获取第二项的 UserRole 数据QVariant data = comboBox->itemData(1, Qt::UserRole);qDebug() << "Item data at index 1 (Banana):" << data.toInt();// 获取第二项的 DisplayRole 数据QVariant display = comboBox->itemData(1, Qt::DisplayRole);qDebug() << "Item data at index 1 (Banana):" << display.toString();
}
11. QIcon itemIcon(int index) const
功能:获取 QComboBox 指定索引 (index) 处的项的图标。
参数:
index:要获取图标的项的索引(从 0 开始)。
返回值:返回 QIcon,即 index 处项的图标。
#include <QComboBox>
#include <QDebug>
#include <QLineEdit>MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{QComboBox *comboBox = new QComboBox(this);comboBox->addItem(QIcon(":/icons/apple.png"), "Apple");comboBox->addItem(QIcon(":/icons/banana.png"), "Banana");// 获取第 1 项的图标QIcon icon = comboBox->itemIcon(1);if (!icon.isNull()) {qDebug() << "Banana has an icon.";} else {qDebug() << "Banana has no icon.";}
}
12. QString itemText(int index) const
功能:获取 QComboBox 指定索引 (index) 处的项的文本。
参数:
index:要获取文本的项的索引。
返回值:
- 返回 QString,即 index 处的项的文本。
- 如果索引无效,则返回空字符串 “”。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Apple");
comboBox->addItem("Banana");// 获取第 1 项的文本
QString text = comboBox->itemText(1);
qDebug() << "Item at index 1:" << text; // 输出 "Banana"
*13. QLineEdit lineEdit() const
功能:获取 QComboBox 内部的 QLineEdit 对象(仅当 QComboBox 设为可编辑模式时 setEditable(true) 生效)。
返回值:
- 返回 QLineEdit*,即 QComboBox 关联的输入框指针。
- 如果 QComboBox 不可编辑,则返回 nullptr。
QComboBox *comboBox = new QComboBox(this);
comboBox->setEditable(true);// 获取 QLineEdit 并设置占位符
QLineEdit *edit = comboBox->lineEdit();
if (edit) {edit->setPlaceholderText("Enter an item...");edit->setStyleSheet("color: blue;");
}
四、信号与槽函数
槽函数:
void clear()
void clearEditText()
void setCurrentIndex(int index)
void setCurrentText(const QString &text)
void setEditText(const QString &text)
1. void clear()
作用:
- 清空 QComboBox 的所有项,但不会影响 QLineEdit 的输入(如果 setEditable(true))。
- 通常用于动态刷新数据。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Apple");
comboBox->addItem("Banana");// 清空所有项
comboBox->clear();
2. void clearEditText()
作用:
- 清空 QComboBox 编辑框的文本,但不会影响列表项(只适用于 setEditable(true))。
- 适用于输入框需要清空但保留选项的情况。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Apple");
comboBox->addItem("Banana");comboBox->setEditable(true);
comboBox->setEditText("Type something...");// 清空编辑框文本
comboBox->clearEditText();
3. void setCurrentIndex(int index)
作用:
- 设置 QComboBox 当前选中的项,index 从 0 开始。
- 如果 index 超出范围,则不做任何操作。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Apple");
comboBox->addItem("Banana");// 让 "Banana" 变为当前选中项(索引 1)
comboBox->setCurrentIndex(1);
4. void setCurrentText(const QString &text)
作用:
- 设置 QComboBox 当前选中的项,匹配 text。
- 如果 text 已经存在于下拉列表,则选中它。
- 如果 text 不存在:如果 setEditable(true),则将 text 作为新输入内容。如果 setEditable(false),则什么都不会发生。
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Apple");
comboBox->addItem("Banana");// 选中 "Banana"
comboBox->setCurrentText("Banana");// 试图选中 "Orange"(如果 `setEditable(false)`,此操作无效)
comboBox->setCurrentText("Orange");
5. void setEditText(const QString &text)
作用:
- 直接设置 QComboBox 编辑框的文本(不会影响选中项)。
- 只在 setEditable(true) 时生效。
QComboBox *comboBox = new QComboBox(this);
comboBox->setEditable(true);
comboBox->addItem("Apple");
comboBox->addItem("Banana");// 设置编辑框文本(不会影响选中项)
comboBox->setEditText("Hello");
信号列表:
void activated(int index)
void currentIndexChanged(const QString &text)
void currentIndexChanged(int index)
void currentTextChanged(const QString &text)
void editTextChanged(const QString &text)
void highlighted(int index)
void textActivated(const QString &text)
void textHighlighted(const QString &text)
1. activated(int index):用户选择项时触发
适用于用户点击项或按 Enter 触发操作,但 不会在代码更改 setCurrentIndex() 时触发。
connect(comboBox, QOverload<int>::of(&QComboBox::activated), this, [](int index) {qDebug() << "Activated item index:" << index;});
2. currentIndexChanged(int index) & currentIndexChanged(QString text)
适用于 监听用户选择或代码变更选项,可以通过 索引 或 文本 监听。
connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [](int index) {qDebug() << "Index changed to:" << index;});connect(comboBox, QOverload<const QString &>::of(&QComboBox::currentIndexChanged), this, [](const QString &text) {qDebug() << "Text changed to:" << text;});
3. currentTextChanged(const QString &text):文本内容变更
适用于监听当前文本变化(包括编辑输入和选择项改变)。
connect(comboBox, &QComboBox::currentTextChanged, this, [](const QString &text) {qDebug() << "Current text changed to:" << text;});
4. editTextChanged(const QString &text):编辑框内容变更
适用于 监听 QComboBox 编辑框实时输入(仅 setEditable(true) 时有效)。
comboBox->setEditable(true); // 启用可编辑模式connect(comboBox, &QComboBox::editTextChanged, this, [](const QString &text) {qDebug() << "User typing:" << text;});
5. highlighted(int index):鼠标悬停高亮
适用于 鼠标悬停时触发(不需要点击),可用于 显示工具提示、预览详情。
connect(comboBox, QOverload<int>::of(&QComboBox::highlighted), this, [](int index) {qDebug() << "Hovered over item index:" << index;});
6. textActivated(const QString &text) & textHighlighted(const QString &text)
和 activated()、highlighted() 相似,但参数为 文本。
connect(comboBox, &QComboBox::textActivated, this, [](const QString &text) {qDebug() << "Activated text:" << text;});connect(comboBox, &QComboBox::textHighlighted, this, [](const QString &text) {qDebug() << "Hovered text:" << text;});