QComboBox提供了下拉列表框的控件。下面简单介绍几个的方法和属性。
(1)addItems
void addItem(const QString &text, const QVariant &userData = QVariant())
void addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
在列表的最后一项添加一个文本内容为test选项
(2)currentText
QString currentText() const
返回下拉列表框中当前选中的文本
(3)count
int count() const
返回当前列表框中选项数量
(4)currentIndex
int currentIndex() const
返回当前列表框中选中文本的序号
简单的案例:
#include "widget.h"
#include <QComboBox>
#include <QLayout>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QComboBox *combobox = new QComboBox(this);
combobox->addItem(tr("Circle"));
combobox->addItem(tr("Pology"));
QGridLayout *mainLayout = new QGridLayout(this);
mainLayout->addWidget(combobox,0,0);
qDebug() << "Now there are " << combobox->count() << "Items";
qDebug() << "The current item is" << combobox->currentText();
}
Widget::~Widget()
{
}
结果:
程序输出:
Now there are 2 Items
The current item is "Circle"
代码2:
//不带图标写法
ui->comboBox->addItem("A1");
ui->comboBox->addItem("A2");
ui->comboBox->addItem("A3");
ui->comboBox->addItem("A4");
ui->comboBox->addItem("A5");
ui->comboBox->addItem("A6");
//带图标写法
ui->comboBox->addItem(icon,QString::asprintf("Item %d",i));
//可以使用QStringList 一次写入多个数据
QStringList strList;
strList<<"A1"<<"A2"<<"A3"<<"A4"<<"A5"<<"A6";
ui->comboBox->addItems(strList);
ui->comboBox->setCurrentIndex(2);
获取ComboBox控件总索引数
//索引为1-6
int intc = ui->comboBox->count();
QString StrIntN=QString::number(intc);
QMessageBox::information(this, "comboBox", StrIntN, QMessageBox::Ok);
获取ComboBox控件当前选中索引:
//索引为0-5
int index = ui->comboBox->currentIndex();//获得索引
QString StrIntN=QString::number(index);
QMessageBox::information(this, "comboBox", StrIntN, QMessageBox::Ok);
获取当前内容:
QMessageBox::information(this, "comboBox", ui->comboBox->currentText(), QMessageBox::Ok);
ui->comboBox->clear(); //清除列表