qt简易计算器 代码
时间: 2024-05-13 12:11:21 浏览: 142
QT计算器(内含完整代码)
Qt简易计算器是一个基于Qt框架开发的简单计算器应用程序。它可以进行基本的数学运算,如加法、减法、乘法和除法。以下是一个示例代码:
```cpp
#include <QApplication>
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建主窗口
QWidget window;
window.setWindowTitle("Qt简易计算器");
// 创建显示结果的文本框
QLineEdit *resultLineEdit = new QLineEdit(&window);
resultLineEdit->setReadOnly(true);
// 创建数字按钮
QPushButton *buttons[10];
for (int i = 0; i < 10; ++i) {
buttons[i] = new QPushButton(QString::number(i), &window);
}
// 创建运算符按钮
QPushButton *addButton = new QPushButton("+", &window);
QPushButton *subtractButton = new QPushButton("-", &window);
QPushButton *multiplyButton = new QPushButton("*", &window);
QPushButton *divideButton = new QPushButton("/", &window);
QPushButton *equalButton = new QPushButton("=", &window);
// 创建布局管理器
QGridLayout *layout = new QGridLayout(&window);
// 设置按钮位置
layout->addWidget(resultLineEdit, 0, 0, 1, 4);
layout->addWidget(buttons, 1, 0);
layout->addWidget(buttons, 1, 1);
layout->addWidget(buttons, 1, 2);
layout->addWidget(addButton, 1, 3);
layout->addWidget(buttons, 2, 0);
layout->addWidget(buttons, 2, 1);
layout->addWidget(buttons, 2, 2);
layout->addWidget(subtractButton, 2, 3);
layout->addWidget(buttons, 3, 0);
layout->addWidget(buttons, 3, 1);
layout->addWidget(buttons, 3, 2 layout->addWidget(multiplyButton, 3, 3);
layout->addWidget(buttons, 4, 0);
layout->addWidget(equalButton, 4, 1);
layout->addWidget(divideButton, 4, 2);
// 连接按钮的点击事件到槽函数
QObject::connect(addButton, &QPushButton::clicked, [&]() {
resultLineEdit->setText(QString::number(resultLineEdit->text().toInt() + resultLineEdit->text().toInt()));
});
QObject::connect(subtractButton, &QPushButton::clicked, [&]() {
resultLineEdit->setText(QString::number(resultLineEdit->text().toInt() - resultLineEdit->text().toInt()));
});
QObject::connect(multiplyButton, &QPushButton::clicked, [&]() {
resultLineEdit->setText(QString::number(resultLineEdit->text().toInt() * resultLineEdit->text().toInt()));
});
QObject::connect(divideButton, &QPushButton::clicked, [&]() {
resultLineEdit->setText(QString::number(resultLineEdit->text().toInt() / resultLineEdit->text().toInt()));
});
QObject::connect(equalButton, &QPushButton::clicked, [&]() {
// 执行等号操作,计算结果
// 这里可以根据需要自行实现
// 示例:将结果显示在文本框中
resultLineEdit->setText("计算结果");
});
// 显示主窗口
window.setLayout(layout);
window.show();
return app.exec();
}
```
这段代码创建了一个简单的计算器界面,包含数字按钮、运算符按钮和一个显示结果的文本框。通过连接按钮的点击事件到相应的槽函数,可以实现基本的计算功能。你可以根据需要自行完善等号按钮的点击事件,实现具体的计算逻辑。
阅读全文