QComboBox 主要的功能是提供一个下拉列表供选择输入。
头文件:
#include<QCombobox>
常用函数:
comboBox->addItem("cxq"); //添加下拉选项
combobox->clear(); //清空下拉项
comboBox->setCurrentIndex(0);//设置当前的索引
combobox->currentText(); //获取当前项的内容
comboBox->itemText(2); //获取第二项的内容
combobox->count(); //获取项的个数
1.添加下拉项
ui->comboBox->addItem("+");
ui->comboBox->addItem("-");
ui->comboBox->addItem("*");
ui->comboBox->addItem("/");
2.可以设置combobox的索引
ui->comboBox->setCurrentIndex(0);
3.当我们需要点击项的时候,可以进行当前项的作用
//把combobox 的索引交给index 为0 1 2 3然后进入switch
int index=comboBox->currentIndex();
switch(index)
{
case 0:result=n1+n2;break;
case 1:result=n1-n2;break;
case 2:result=n1*n2;break;
case 3:result=n1/n2;break;
}
combobox的应用:简单计算器
jisuanqi.cpp
#include "jisuanqi.h"
#include "ui_jisuanqi.h"
jisuanqi::jisuanqi(QWidget *parent) :
QWidget(parent),
ui(new Ui::jisuanqi)
{
ui->setupUi(this);
hboxlayout=new QHBoxLayout;
firstEdit=new QLineEdit;
secondEdit=new QLineEdit;
resultEdit=new QLineEdit;
pushbutton=new QPushButton("=");
comboBox=new QComboBox;
comboBox->addItem("+");
comboBox->addItem("-");
comboBox->addItem("*");
comboBox->addItem("/");
//设置combobox的索引,方便寻找
hboxlayout->addWidget(firstEdit,0,0);
hboxlayout->addWidget(comboBox,1,0);
hboxlayout->addWidget(secondEdit,2,0);
hboxlayout->addWidget(pushbutton,3,0);
hboxlayout->addWidget(resultEdit,4,0);
comboBox->setCurrentIndex(0);
//设置为只读
resultEdit->setReadOnly(true);
//设置布局
setLayout(hboxlayout);
connect(pushbutton,&QPushButton::clicked,this,&jisuanqi::setresult);
}
jisuanqi::~jisuanqi()
{
delete ui;
}
void jisuanqi::setresult()
{
//获取到第一个输入框的字符转为整型
int n1=firstEdit->text().toInt();
//获取到第二个输入框的字符转为整型
int n2=secondEdit->text().toInt();
int result=0;
//把combobox 的索引交给index 为0 1 2 3然后进入switch
int index=comboBox->currentIndex();
switch(index)
{
case 0:result=n1+n2;break;
case 1:result=n1-n2;break;
case 2:result=n1*n2;break;
case 3:result=n1/n2;break;
}
//将结果转化为字符串类型
QString str=QString("%1").arg(result);
//将得到的结果字符串传给reaultEidt
resultEdit->setText(str);
}
jisuanqi.h
#ifndef JISUANQI_H
#define JISUANQI_H
#include <QWidget>
#include <QLayout>//布局
#include <QLineEdit>//文编编辑区
#include <QComboBox>//下拉按钮
#include <QPushButton>//按钮
namespace Ui {
class jisuanqi;
}
class jisuanqi : public QWidget
{
Q_OBJECT
public:
explicit jisuanqi(QWidget *parent = nullptr);
~jisuanqi();
public slots:
void setresult();
private:
Ui::jisuanqi *ui;
QHBoxLayout *hboxlayout;
QLineEdit *firstEdit;
QLineEdit *secondEdit;
QLineEdit *resultEdit;
QPushButton *pushbutton;
QComboBox *comboBox;
};
#endif // JISUANQI_H
demo效果如下: