qt实现计算器加减乘除
时间: 2023-10-21 18:06:51 浏览: 137
用qt实现计算器
可以使用Qt的QLineEdit和QPushButton来实现简单的计算器加减乘除功能。在QPushButton的clicked()信号中,读取QLineEdit中的文本,然后进行相应的计算。具体实现如下:
```cpp
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>
#include <QtCore/QRegExp>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget w;
QLineEdit *lineEdit = new QLineEdit; // 输入框
QRegExp regExp("[0-9]*"); // 正则表达式,限制只能输入数字
lineEdit->setValidator(new QRegExpValidator(regExp, lineEdit));
lineEdit->setAlignment(Qt::AlignRight); // 文本右对齐
QPushButton *btnAdd = new QPushButton("+"); // 加号按钮
QPushButton *btnSub = new QPushButton("-"); // 减号按钮
QPushButton *btnMul = new QPushButton("*"); // 乘号按钮
QPushButton *btnDiv = new QPushButton("/"); // 除号按钮
// 计算器布局
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(lineEdit);
layout->addWidget(btnAdd);
layout->addWidget(btnSub);
layout->addWidget(btnMul);
layout->addWidget(btnDiv);
w.setLayout(layout);
QObject::connect(btnAdd, &QPushButton::clicked, [&]() {
double num1 = lineEdit->text().toDouble();
double num2 = lineEdit->text().section('+', 1).toDouble();
double result = num1 + num2;
lineEdit->setText(QString::number(result)); });
QObject::connect(btnSub, &QPushButton::clicked, [&]() {
double num1 = lineEdit->text().toDouble(); double num2 = lineEdit->text().section('-', 1).toDouble();
double result = num1 - num2;
lineEdit->setText(QString::number(result));
});
QObject::connect(btnMul, &QPushButton::clicked, [&]() {
double num1 = lineEdit->text().toDouble();
double num2 = lineEdit->text().section('*', 1).toDouble();
double result = num1 * num2;
lineEdit->setText(QString::number(result));
});
QObject::connect(btnDiv, &QPushButton::clicked, [&]() {
double num1 = lineEdit->text().toDouble();
double num2 = lineEdit->text().section('/', 1).toDouble();
double result = num1 / num2;
lineEdit->setText(QString::number(result));
});
w.show();
return app.exec();
}
```
阅读全文