QComboBox是QT GUI中的下拉列表框。
class Q_GUI_EXPORT QComboBox : public QWidget
{
Q_OBJECT
常用方法和属性:
(1)addItems
void addItems ( const QStringList & texts )在QComboBox的最后添加一项。
(2)count
int count () const返回列表项总数。
(3)currentIndex
int currentIndex () const当前显示的列表项序号。
(4)currentText
QString currentText () const返回当前显示的文本。
(5)insertItem
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 )
插入一项或多项至序号index处。
(6)insertSeparator
在序号为index的项前插入分隔线
(7)setItemText
改变序号为index项的文本。
示例如下:
#include "mainwindow.h"
#include <QPushButton>
#include <QLineEdit>
#include <QLayout>
#include <QLabel>
#include <QComboBox>
#include <QMessageBox>
#include <QDialog>
mainwindow::mainwindow(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
QGridLayout *gridLayout=new QGridLayout;
//它的含义是:第几列伸展的权重
//建议:在设置的时候,如果设置列,每列都要分配权重,否则,结果可能不是自己想要的。
gridLayout->setColumnStretch(0,1);
gridLayout->setColumnStretch(1,2);
//设置边框大小。所谓边框,应该有4边,这里是部件边缘相对父部件的间距。
gridLayout->setMargin(5);
QLabel *label=new QLabel(QWidget::tr("Sex:"));
cbo_sex = new QComboBox();
cbo_sex->addItem(QWidget::tr("male"));
cbo_sex->addItem(QWidget::tr("female"));
cbo_sex->insertItem(2, tr("Insert item"));
cbo_sex->insertSeparator(2);
gridLayout->addWidget(label,0,0);
gridLayout->addWidget(cbo_sex, 0, 1);
//gridLayout->addWidget();
QHBoxLayout *bomLayout=new QHBoxLayout;
QPushButton *btn=new QPushButton(QWidget::tr("Select"));
bomLayout->addStretch();
bomLayout->addWidget(btn);
bomLayout->addStretch();
QVBoxLayout *mainLayout=new QVBoxLayout;
mainLayout->addLayout(gridLayout);
mainLayout->addLayout(bomLayout);
QWidget *mainWidget=new QWidget;
mainWidget->setLayout(mainLayout);
setCentralWidget(mainWidget);
connect(cbo_sex, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(on_sel_sex(const QString &)));
connect(btn, SIGNAL(clicked()), this, SLOT(on_click_sel()));
}
//void setSpacing(int)
//它的含义是设置间距大小。这是指元素的间距的小。
//如果GridLayout中,它指的是单元格之间的间距。也可以理解为表格内部线的粗细程度。
//在英语中,strech是伸缩、伸展的意思。下面的方法,也可以在一定区域内容设置行列之间的宽高伸缩比重。
//void QGridLayout::setRowStretch(int row, int stretch)
//它的含义是:第几行伸展的权重
mainwindow::~mainwindow()
{
}
void mainwindow::on_sel_sex(const QString &text)
{
QString str;
str="You select "+text;
QMessageBox::information(this,tr("info"),str);
}
void mainwindow::on_click_sel()
{
QString str;
str="You select "+cbo_sex->currentText();
QMessageBox::information(this,tr("info"),str);
}
界面如下所示: