QComboBox提供了下拉列表框的控件。下面简单介绍几个的方法和属性。(1)addItemsvoid addItem(const QString &text, const QVariant &userData = QVariant())void addItem(const QIcon &icon, const QString &text, const QVariant &userData = QVariant())在列表的最后一项添加一个文本内容为test选项(2)currentTextQString currentText() const返回下拉列表框中当前选中的文本(3)countint count() const返回当前列表框中选项数量(4)currentIndexint 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 ItemsThe 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-6int intc = ui->comboBox->count();QString StrIntN=QString::number(intc);QMessageBox::information(this, "comboBox", StrIntN, QMessageBox::Ok);
获取ComboBox控件当前选中索引://索引为0-5int 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(); //清除列表