初学Qt,制作一个简单计算器。
先上效果图:
上面显示框,用于显示输入:
如:1*2-(3-8)+2*6
按下等于键,下面显示框显示输出结果:
1,计算器界面设计
因为本人初学,就直接在ui界面画出所需界面了,如下:
在界面画好之后,记得要布局,让其界面一直处于居中状态,另外可以右键,选择修改每个控件名字,便于对各个控件编程。
2,总体设计思路。
由界面设计。我们可以看出,有两个显示框,当我们输入表达式时,要实时显示到界面上,那我们可以将上面的框用于显示输入表达式,下面的框用于显示输入的数据及最后的运算结果。
我们定义一个结构体:
struct put_ctrl_t{
QString old_put; //用于表达式的存储
QString new_put; //用于输入的数据存储
int brackets_cnt; //左括号输入个数
int update_flag; //当new_put为“0”时,重新输入0表示更新置1
};
计算器是模仿win10的自带的标准计算器,显示方式和其相似。
当我们输入1+2=时,
(1)—>input 1
old_put = “0”;//初始值
new_put = “1”;
(2)—->input +
old_put = “1+”;//显示到上框
new_put = “0”;//初始化
(3)—->input 2
old_put = “1+”;//显示到上框
new_put = “2”;
(4)—->input =
old_put = “1+2”;//不显示,计算结果显示到下框,上框清空
new_put = “0”;
old_put = “0”;//初始化
3,计算器按键输入信号绑定connect。
/*所有按键,信号连接*/
connect(ui>button_0,SIGNAL(clicked()),this,SLOT(push_button_0()));
connect(ui->button_1,SIGNAL(clicked()),this,SLOT(push_button_1()));
connect(ui->button_2,SIGNAL(clicked()),this,SLOT(push_button_2()));
connect(ui->button_3,SIGNAL(clicked()),this,SLOT(push_button_3()));
connect(ui->button_4,SIGNAL(clicked()),this,SLOT(push_button_4()));
connect(ui->button_5,SIGNAL(clicked()),this,SLOT(push_button_5()));
connect(ui->button_6,SIGNAL(clicked()),this,SLOT(push_button_6()));
connect(ui->button_7,SIGNAL(clicked()),this,SLOT(push_button_7()));
connect(ui->button_8,SIGNAL(clicked()),this,SLOT(push_button_8()));
connect(ui->button_9,SIGNAL(clicked()),this,SLOT(push_button_9()));
connect(ui->button_point,SIGNAL(clicked()),this,SLOT(push_button_point()));
connect(ui->button_left,SIGNAL(clicked()),this,SLOT(push_button_left()));
connect(ui->button_right,SIGNAL(clicked()),this,SLOT(push_button_right()));
connect(ui->button_add,SIGNAL(clicked()),this,SLOT(push_button_add()));
connect(ui->button_minus,SIGNAL(clicked()),this,SLOT(push_button_minus()));
connect(ui->button_ride,SIGNAL(clicked()),this,SLOT(push_button_ride()));
connect(ui->button_divide,SIGNAL(clicked()),this,SLOT(push_button_divide()));
connect(ui->button_equal,SIGNAL(clicked()),this,SLOT(push_button_equal()));
connect(ui->button_AC,SIGNAL(clicked()),this,SLOT(push_button_AC()));
connect(ui>button_CE,SIGNAL(clicked()),this,SLOT(push_button_CE()));
4,按键输入处理函数。主要注意的就是(),+,-,*,/,小数点的输入,数字输入主要注意0的输入即可,下方是详细代码。仔细看一下应该就可以懂得,没有很多复杂的操作,都是字符串和逻辑的操作。
/*数据按键输入*/
void Calculator::push_button_0()
{
if(put_ctrl.new_put == "0"){
put_ctrl.new_put = "0";
put_ctrl.update_flag = 1;
}
else
put_ctrl.new_put += "0";
ui->put_data->setText(put_ctrl.new_put);
}
void Calculator::push_button_1()
{
if(put_ctrl.new_put == "0")
put_ctrl.new_put =