Qt入门-下拉列表框QComboBox类

     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

void insertSeparator ( int index )

在序号为index的项前插入分隔线


(7)setItemText

void setItemText ( int index, const QString & text )

改变序号为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();
}


编译运行,界面如下:

Qt入门-下拉列表框QComboBox类_第1张图片

 

你可能感兴趣的:(list,object,Class,insert,qt,Signal)