C++ Qt QComboBox使用教程
C++ Qt QComboBox使用教程
目录
(1)添加数据项
(2)获取当前文本
(3)选项变化时触发的信号
(4)本例全部代码
QComboBox提供了下拉列表选择的功能,使用方法如下:
(1)添加数据项
//给combobox添加内容项ui->comboBox->addItem("11");ui->comboBox->addItem("12");ui->comboBox->addItem("13");ui->comboBox->addItem("14");ui->comboBox->addItem("15");ui->comboBox->addItem("16");
(2)获取当前文本
//获取combobox当前内容QString text = ui->comboBox->currentText();
(3)选项变化时触发的信号
查看QComboBox的代码可知,有如下信号:
Q_SIGNALS:void editTextChanged(const QString &);void activated(int index);void activated(const QString &);void highlighted(int index);void highlighted(const QString &);void currentIndexChanged(int index);void currentIndexChanged(const QString &);void currentTextChanged(const QString &);
QComboBox的选择项发生变化时,会触发currentIndexChanged信号,参数index会传递给槽函数,该信号有重载版本,参数QString会传给参函数当前选择的内容,QtCreator在编译时可能会报错为了防止混淆建议使用Qt4的信号槽。
//combobox内容选择变化时触发currentIndexChanged信号,注意这里用Qt4信号槽比较好,避免混淆
connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboxSelect(int)));
可以用QMessageBox验证选择的结果:
void MainWindow::onComboxSelect(int index)
{//获取combobox当前内容QString text = ui->comboBox->currentText();QMessageBox::information(this, "title", "your select item is " + text, NULL);
}
如下图
(4)本例全部代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);//给combobox添加内容项ui->comboBox->addItem("11");ui->comboBox->addItem("12");ui->comboBox->addItem("13");ui->comboBox->addItem("14");ui->comboBox->addItem("15");ui->comboBox->addItem("16");//combobox内容选择变化时触发currentIndexChanged信号,注意这里用Qt4信号槽比较好,避免混淆connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboxSelect(int)));
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::onComboxSelect(int index)
{//获取combobox当前内容QString text = ui->comboBox->currentText();QMessageBox::information(this, "title", "your select item is " + text, NULL);
}