您的位置:首页 > 产品设计 > UI/UE

(4)qt5制作简易计算器详细步骤(ui界面)

2017-12-06 13:13 706 查看
网上很多资源都是纯代码的,本文使用ui界面做

(1)新建项目,一路默认“下一步”,完成建立







(2)

选择3个Line Edit 1个Push Button 2个Label

布局并且改名以及改变对象名称(单击右键)



(3)Mainwindow.h中添加槽

private slots:
void calcSlot();



(4)mainwindow.cpp中添加

void MainWindow::calcSlot()
{
int firstvalue=ui->firstValue->text().toInt();//取出第一个文本转化为整数类型
int secondvalue=ui->secondValue->text().toInt();
int resultvalue=firstvalue+secondvalue;
ui->resultValue->setText(QString::number(resultvalue));
}



(5)连接信号与槽

QObject::connect(ui->calcButton,SIGNAL(clicked()),this,SLOT(calcSlot());
(6)ctrl+r运行结果(忘了截图了~~)

(7)下面将加法运算变为四则运算

将label为加号的删除并替换为ComboBox

编辑Combo Box,右键单击选择“编辑项目”
添加+ - * /



(8)修改mainwindow.cpp为

void MainWindow::calcSlot()
{
int firstvalue=ui->firstValue->text().toInt();//取出第一个文本转化为整数类型
int secondvalue=ui->secondValue->text().toInt();
int resultvalue;
if(ui->comboBox->currentIndex()==0)
{
resultvalue=firstvalue+secondvalue;
ui->resultValue->setText(QString::number(resultvalue));
}
if(ui->comboBox->currentIndex()==1)
{
resultvalue=firstvalue-secondvalue;
ui->resultValue->setText(QString::number(resultvalue));
}
if(ui->comboBox->currentIndex()==2)
{
resultvalue=firstvalue*secondvalue;
ui->resultValue->setText(QString::number(resultvalue));
}
if(ui->comboBox->currentIndex()==3)
{
if(secondvalue==0)
{
return;
}
resultvalue=firstvalue/secondvalue;
ui->resultValue->setText(QString::number(resultvalue));
}
}



(9)

Ctrl+r结果如下

运行1



运行2



(10)现在添加一个弹出对话框显示消息

Mainwindow.h中添加

#include<QMessageBox>



(11)

Mainwindow.cpp中添加

QMessageBox::information(this,"Result",QString::number(resultvalue));//result为标题

QMessageBox::information(this,"ErrorMessage","SecondCant`tbeZero!!!");




(12)运行结果1



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: