qt做一个加减法的计算器
时间: 2023-07-25 13:42:21 浏览: 183
好的,下面是一个简单的加减法计算器的示例代码:
```c++
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 创建主窗口
QWidget *mainWindow = new QWidget;
mainWindow->setWindowTitle("加减法计算器");
// 创建输入框和标签
QLabel *num1Label = new QLabel("数值1:");
QLineEdit *num1Edit = new QLineEdit;
QLabel *num2Label = new QLabel("数值2:");
QLineEdit *num2Edit = new QLineEdit;
QLabel *resultLabel = new QLabel("结果:");
QLineEdit *resultEdit = new QLineEdit;
resultEdit->setReadOnly(true);
// 创建按钮
QPushButton *addButton = new QPushButton("加");
QPushButton *subButton = new QPushButton("减");
// 创建布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(num1Label);
layout->addWidget(num1Edit);
layout->addWidget(num2Label);
layout->addWidget(num2Edit);
layout->addWidget(resultLabel);
layout->addWidget(resultEdit);
layout->addWidget(addButton);
layout->addWidget(subButton);
mainWindow->setLayout(layout);
// 连接槽函数
QObject::connect(addButton, &QPushButton::clicked, [=]() {
bool ok;
double num1 = num1Edit->text().toDouble(&ok);
double num2 = num2Edit->text().toDouble(&ok);
double result = num1 + num2;
resultEdit->setText(QString::number(result));
});
QObject::connect(subButton, &QPushButton::clicked, [=]() {
bool ok;
double num1 = num1Edit->text().toDouble(&ok);
double num2 = num2Edit->text().toDouble(&ok);
double result = num1 - num2;
resultEdit->setText(QString::number(result));
});
// 显示主窗口
mainWindow->show();
return a.exec();
}
```
该示例代码使用了Qt的基础控件,包括QLabel、QLineEdit、QPushButton等。代码中创建了一个垂直布局,并将输入框、标签和按钮添加到布局中。使用QObject::connect函数连接了按钮的clicked信号和相应的槽函数,通过text().toDouble()函数将输入框中的字符串转换为数值,并进行加减法运算,最后将结果显示在输出框中。
阅读全文