刚接触Qt,没有使用QtDesigner来编写ui文件,纯vs编写
calculator.h与calculator.cpp由自己编写,main.cpp与ui_calculator.h由vs生成
calculator.h
#pragma once
#pragma execution_character_set("utf-8")
#include <QtWidgets/QMainWindow>
#include "ui_calculator.h"
#include <QLabel>
#include <QLineEdit>
#include <QRadioButton>
#include <QPushButton>
#include <QGridLayout>
#include <QButtonGroup>
class calculator : public QMainWindow
{
Q_OBJECT
public:
calculator(QWidget *parent = Q_NULLPTR);
public slots :
void jisuan();
private:
Ui::calculatorClass ui;
QLabel *number_1;
QLabel *number_2;
QLineEdit *numline_1;
QLineEdit *numline_2;
QButtonGroup *oper;
QRadioButton *plus;
QRadioButton *minus;
QRadioButton *multiply;
QRadioButton *divide;
QLabel *resultlabel;
QLineEdit *result;
QPushButton *cal;
QGridLayout *mainlayout;
};
calculator.cpp
#include "calculator.h"
calculator::calculator(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
number_1 = new QLabel("数字1:");
number_2 = new QLabel("数字2:");
numline_1 = new QLineEdit;
numline_2 = new QLineEdit;
QRegExp regx("[0-9]+$");
QValidator *validator = new QRegExpValidator(regx);
numline_1->setValidator(validator);
numline_2->setValidator(validator);//限制输入的为数字
oper = new QButtonGroup;
plus = new QRadioButton("+");
minus = new QRadioButton("-");
multiply = new QRadioButton("*");
divide = new QRadioButton("/");
oper->addButton(plus);
oper->addButton(minus);
oper->addButton(multiply);
oper->addButton(divide);
oper->setExclusive(true);
resultlabel = new QLabel("计算结果:");
result = new QLineEdit;
cal = new QPushButton("计算");
cal->setShortcut(QKeySequence(QLatin1String("Enter")));
mainlayout = new QGridLayout(ui.centralWidget);
mainlayout->addWidget(number_1, 0, 0);
mainlayout->addWidget(numline_1, 0, 1,1,3);
mainlayout->addWidget(number_2, 1, 0);
mainlayout->addWidget(numline_2, 1, 1,1,3);
mainlayout->addWidget(plus,2,0);
mainlayout->addWidget(minus, 2, 1);
mainlayout->addWidget(multiply, 2, 2);
mainlayout->addWidget(divide, 2, 3);
mainlayout->addWidget(cal, 3, 0,1,4);
mainlayout->addWidget(resultlabel, 4, 0);
mainlayout->addWidget(result, 4, 1,1,3);
connect(cal, SIGNAL(clicked()), this, SLOT(jisuan()));
}
void calculator::jisuan()
{
QString n1 = numline_1->text();
QString n2 = numline_2->text();
double num1 = n1.toDouble();
double num2 = n2.toDouble();
double res = 0.0;
if (plus->isChecked())
{
res = num1 + num2;
}
if (minus->isChecked())
{
res = num1 - num2;
}
if (multiply->isChecked())
{
res = num1 * num2;
}
if (divide->isChecked())
{
res = num1 / num2;
}
QRegExp rx;
rx.setPattern("(\\.){0,1}0+$");
QString res2= QString("%1").arg(res, 0, 'f', -1).replace(rx, "");
//使用正则表达式去除小数后多余的0
result->setText(res2);
if (divide->isChecked() && num2 == 0)
{
result->setText("Error");
}
}
效果如图