目录
一、功能
二、代码
三、结果
功能
通过界面输入能实现基本的加减乘除运算,输错能实现退格、清屏。
代码
widget.cpp
#include "widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
le_lcd = new QLineEdit;
bt_chop = new QPushButton("<");
for(int i=0; i<10; i++)
bt_num[i] = new QPushButton(QString::number(i));
bt_add = new QPushButton("+");
bt_sub = new QPushButton("-");
bt_mul = new QPushButton("*");
bt_div = new QPushButton("/");
bt_calc = new QPushButton("=");
QHBoxLayout *qhbox = new QHBoxLayout;
qhbox->addWidget(le_lcd);
qhbox->addWidget(bt_chop);
//布局
QGridLayout *qgbox = new QGridLayout;
int i = 9;
for(int y=0; y<3; y++)
for(int x=0; x<3; x++)
qgbox->addWidget(bt_num[i--], y, x);
qgbox->addWidget(bt_num[0],3,0);
qgbox->addWidget(bt_add, 0, 3);
qgbox->addWidget(bt_sub, 1, 3);
qgbox->addWidget(bt_mul, 2, 3);
qgbox->addWidget(bt_div, 3, 3);
qgbox->addWidget(bt_calc, 3, 1, 1, 2);
QVBoxLayout *qvbox = new QVBoxLayout;
qvbox->addLayout(qhbox);
qvbox->addLayout(qgbox);
setLayout(qvbox);
//关联槽函数
for(int i=0; i<10; i++)
connect(bt_num[i], SIGNAL(clicked(bool)), this, SLOT(num_pressed()));
connect(bt_chop, SIGNAL(clicked(bool)), this, SLOT(del_num()));
connect(bt_add, SIGNAL(clicked(bool)), this, SLOT(get_op()));
connect(bt_sub, SIGNAL(clicked(bool)), this, SLOT(get_op()));
connect(bt_mul, SIGNAL(clicked(bool)), this, SLOT(get_op()));
connect(bt_div, SIGNAL(clicked(bool)), this, SLOT(get_op()));
connect(bt_calc, SIGNAL(clicked(bool)), this, SLOT(calculate()));
}
Widget::~Widget()
{
}
void Widget::get_op()
{
QPushButton *xbt = static_cast<QPushButton*>( sender() );
op = xbt->text().toStdString().c_str()[0];
data1 = le_lcd->text().toInt();
le_lcd->clear();
}
void Widget::calculate()
{
data2 = le_lcd->text().toInt();
int answer;
switch (op) {
case '+':
answer = data1 + data2;
break;
case '-':
answer = data1 - data2;
break;
case '*':
answer = data1 * data2;
break;
case '/':
answer = data1 / data2;
break;
default:
break;
}
le_lcd->setText(QString::number(answer));
}
void Widget::del_num()
{
QString str = le_lcd->text();
str.chop(1);
le_lcd->setText(str);
}
void Widget::num_pressed(void)
{
QPushButton *xbt = static_cast<QPushButton*>( sender() );
le_lcd->setText(le_lcd->text().append(xbt->text()));
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
class Widget : public QWidget
{
Q_OBJECT
public slots:
void num_pressed(void);
void del_num(void);
void get_op(void);
void calculate();
public:
Widget(QWidget *parent = 0);
~Widget();
QLineEdit *le_lcd;
QPushButton *bt_num[10];
QPushButton *bt_add;
QPushButton *bt_sub;
QPushButton *bt_mul;
QPushButton *bt_div;
QPushButton *bt_calc;
QPushButton *bt_chop;
char op;
int data1;
int data2;
};
#endif
结果