基于qt用c++类思想写一个简易计算器
时间: 2024-09-30 14:07:15 浏览: 37
基于C++ QT实现的简易计算器源码
5星 · 资源好评率100%
在Qt框架下使用C++编写一个简单的计算器,你可以创建一个类来封装加、减、乘、除的功能。首先,我们需要包含必要的头文件,并设置基础类结构:
```cpp
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QMessageBox>
class Calculator : public QWidget {
Q_OBJECT
public:
explicit Calculator(QWidget *parent = nullptr);
~Calculator();
private slots:
void on_add_button_clicked();
void on_subtract_button_clicked();
void on_multiply_button_clicked();
void on_divide_button_clicked();
void on_clear_button_clicked();
private:
QLineEdit *display;
QPushButton *addButton, *subtractButton, *multiplyButton, *divideButton, *clearButton;
};
```
接下来,我们实现各个槽函数,处理按钮点击事件以及输入显示:
```cpp
Calculator::Calculator(QWidget *parent) : QWidget(parent)
{
setLayout(new QVBoxLayout());
display = new QLineEdit(this);
display->setAlignment(Qt::AlignRight);
addButton = new QPushButton("+", this);
subtractButton = new QPushButton("-", this);
multiplyButton = new QPushButton("*", this);
divideButton = new QPushButton("/", this);
clearButton = new QPushButton("C", this);
connect(addButton, &QPushButton::clicked, this, &Calculator::on_add_button_clicked);
// 添加其他按钮的连接...
layout()->addWidget(display);
layout()->addWidget(addButton);
// 添加其他按钮...
}
// ...实现点击事件处理函数,如:
void Calculator::on_add_button_clicked()
{
double num1 = display->text().toDouble(), num2;
if (num1 == 0 || !display->hasFocus()) {
QMessageBox::warning(this, "警告", "请输入两个数字再进行计算");
return;
}
num2 = display->text().toDouble();
display->setText(QString::number(num1 + num2));
}
```
最后,主函数部分启动应用:
```cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Calculator calculator;
calculator.show();
return app.exec();
}
```
阅读全文