概述:
QComboBox控件是按钮和弹出列表的组合;
组合框是显示当前内容的选择类控件,并且可以弹出可选项列表;
包含很多灵活使用的属性:
1.添加项
addItem(const QString &text, const QVariant &userData = QVariant())
addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
addItems(const QStringList &texts)
2.移除项
removeItem(int index)
3.插入分隔符
insertSeparator(int index)
4.设置可编辑
setEditable(bool editable)
5.设置插入策略
setInsertPolicy(QComboBox::InsertPolicy policy)
6.是否可以输入重复项
void setDuplicatesEnabled(bool enable)
7.设置调整策略
setSizeAdjustPolicy(QComboBox::SizeAdjustPolicy policy)
代码示例:
.h:
#pragma once
/*
* @功能:实现ComBox控件可编辑、下拉选项、设置图标、输入项进行添加、原有项修改等操作;
* @时间:2021-3-30
* @作者:Fantast
*/
#include <QtWidgets/QWidget>
#include "ui_comBoxTest.h"
#include <QComboBox>
#include <QHBoxLayout>
class comBoxTest : public QWidget
{
Q_OBJECT
public:
comBoxTest(QWidget *parent = Q_NULLPTR);
private:
void init();
private:
Ui::comBoxTestClass ui;
};
#include "comBoxTest.h"
comBoxTest::comBoxTest(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
setStyleSheet("background-color:rgb(41, 73, 84)");
init();
}
void comBoxTest::init()
{
QComboBox *comboBox = new QComboBox;
comboBox->setEditable(true); //设置可编辑
comboBox->setDuplicatesEnabled(true); //此属性保留用户是否可以在组合框中输入重复项
comboBox->insertSeparator(0); //插入分隔符
comboBox->setInsertPolicy(QComboBox::InsertAtCurrent);//当前字符串被替换
for (int i = 0; i < 5;i++)
{
comboBox->addItem(/*QIcon(":/Resources/image/print.png"),*/ QString::fromLocal8Bit("打印%1").arg(i));
}
comboBox->setItemIcon(1, QIcon(":/Resources/image/print_preview.png"));
comboBox->setItemIcon(2, QIcon(":/Resources/image/save.png"));
comboBox->setItemIcon(3, QIcon(":/Resources/image/save_as.png"));
comboBox->setItemIcon(4, QIcon(":/Resources/image/print.png"));
comboBox->setItemIcon(5, QIcon(":/Resources/image/page_setup.png"));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(comboBox);
this->setLayout(layout);
this->setWindowTitle("Fantast");
}