QT入门项目–简易计算器
一、前言
C语言快要结课了,自然少不了大作业,在众多选项中看中了简易计算器(其实每一项都研究了,发现自己太菜只能选计算器)。
虽然是C语言大作业,但代码是C++,作业要求推荐图形设计使用MFC,在B站看了几个教程后感觉实在接受不了(本来时间就少,MFC学起来太花时间了,而且不支持跨平台),最后看上了QT(太香了)。QT入门是看的吴健老师的教程。简单了解后就开始编写代码了,教程不知道什么原因,后面都缺失了,不过前面的基础篇也够用了,不会的就查手册,或者上网查询,没必要都记下来,也记不下来,边写边查最好了。
计算器的主要实现就是通过槽函数获取按钮信息,用QString储存表达式,经过检查和运算后将结果显示再labl上,表达式的运算利用逆波兰表达式(后缀表达式)实现,不知道该算法的指路C++栈的应用——后缀表达式求值、中缀表达式到后缀表达式的转换,本人也是在此博客基础上修改实现(其实跟没改一样)。计算器的核心也是这个算法和检查机制(之前并没有加检查机制,后面自己找BUG,出现一个改一个)。
二、运行界面
计算器加了个背景音乐,主要是为了排版好看。
三、代码
首先是dialog,因为计算器只有一个界面,所有没有使用mianwindow
dialog.cpp
主要是链接模型代码
#include "dialog.h"
#include "ui_dialog.h"
#include "doexpr.h"
#include "check.h"
#include <QMessageBox>
#include <QString>
const double PI = 3.14159265358;
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog) //构造函数
{
ui->setupUi(this);
this->setWindowFlags(Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint); //去除窗口右上角“?”
this->player->setMedia(QUrl("music/background.mp3"));
this->player->setVolume(50);
this->temp = "";
this->doExpr = false;
this->loopExpr = false;
}
Dialog::~Dialog() //析构函数
{
delete ui;
}
void Dialog::on_btn_0_clicked()
{
//按钮0槽函数
if(this->temp != "" && this->temp != "0") //防止出现多位0
{
this->temp += this->ui->btn_0->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp); //判断是否已经进行过运算
else
{
this->temp = ""; //若已进行运算,将文本置空
this->temp += this->ui->btn_0->text();
this->ui->lbl_display->setText(this->temp); //显示文本
this->loopExpr = false;
}
}
else //若未输入其他按钮,只显示一个0
{
this->temp = "0";
this->ui->lbl_display->setText(this->temp);
}
}
void Dialog::on_btn_1_clicked()
{
//按钮1槽函数
this->temp += this->ui->btn_1->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp);
else
{
this->temp = "";
this->temp += this->ui->btn_1->text();
this->ui->lbl_display->setText(this->temp);
this->loopExpr = false;
}
}
void Dialog::on_btn_2_clicked()
{
//按钮2槽函数
this->temp += this->ui->btn_2->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp);
else
{
this->temp = "";
this->temp += this->ui->btn_2->text();
this->ui->lbl_display->setText(this->temp);
this->loopExpr = false;
}
}
void Dialog::on_btn_3_clicked()
{
//按钮3槽函数
this->temp += this->ui->btn_3->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp);
else
{
this->temp = "";
this->temp += this->ui->btn_3->text();
this->ui->lbl_display->setText(this->temp);
this->loopExpr = false;
}
}
void Dialog::on_btn_4_clicked()
{
//按钮4槽函数
this->temp += this->ui->btn_4->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp);
else
{
this->temp = "";
this->temp += this->ui->btn_4->text();
this->ui->lbl_display->setText(this->temp);
this->loopExpr = false;
}
}
void Dialog::on_btn_5_clicked()
{
//按钮5槽函数
this->temp += this->ui->btn_5->text();
if(!this->loopExpr)
this->ui->lbl_display->setText(this->temp);
else
{
this->temp = "";
this->temp += this->ui->btn_5->text(