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項的文本。
示例:
Window.h
- #ifndef __WINDOW_H__
- #define __WINDOW_H__
- #include <QMainWindow>
- #include <QPushButton>
- #include <QLineEdit>
- #include <QLayout>
- #include <QLabel>
- #include <QComboBox>
- #include <QMessageBox>
- #include <QDialog>
- class Window : public QMainWindow
- {
- Q_OBJECT
- public:
- Window(QWidget *parent = NULL):QMainWindow(parent)
- {
- QGridLayout *gridLayout = new QGridLayout;
- gridLayout->setColumnStretch(0, 1);
- gridLayout->setColumnStretch(1, 3);
- gridLayout->setMargin(10);
- QLabel *lbl_caption = 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(lbl_caption, 0, 0);
- gridLayout->addWidget(cbo_sex, 0, 1);
- 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()));
- }
- private:
- QComboBox *cbo_sex;
- private slots:
- void on_sel_sex(const QString &text)
- {
- QString str;
- str = "You select " + text;
- QMessageBox::information(this, tr("Info"), str);
- }
- void on_click_sel()
- {
- QString str;
- str = "You select " + cbo_sex->currentText();
- QMessageBox::information(this, tr("Info"), str);
- }
- };
- #endif
main.cpp
- #include <QApplication>
- #include <QDialog>
- #include "Window.h"
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Window *mainWindow = new Window;
- mainWindow->resize(200, 100);
- mainWindow->setWindowTitle(QWidget::tr("Qt Test"));
- mainWindow->show();
- return a.exec();
- }
編譯運行,界面如下: