qt项目实例
时间: 2023-07-03 18:27:33 浏览: 100
好的,这里给您提供一个简单的Qt项目实例,就是一个简单的计算器程序。以下是该程序的主要功能:
- 可以进行加、减、乘、除四则运算。
- 可以输入小数和负数。
- 可以进行连续计算。
以下是该程序的源代码:
```cpp
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建主窗口
QWidget *mainWindow = new QWidget;
mainWindow->setWindowTitle("简单计算器");
// 创建文本框和按钮
QLineEdit *lineEdit = new QLineEdit;
QPushButton *buttonAdd = new QPushButton("+");
QPushButton *buttonSubtract = new QPushButton("-");
QPushButton *buttonMultiply = new QPushButton("×");
QPushButton *buttonDivide = new QPushButton("÷");
QPushButton *buttonClear = new QPushButton("清除");
QPushButton *buttonEqual = new QPushButton("=");
// 创建布局
QGridLayout *layout = new QGridLayout;
layout->addWidget(lineEdit, 0, 0, 1, 4);
layout->addWidget(buttonAdd, 1, 0);
layout->addWidget(buttonSubtract, 1, 1);
layout->addWidget(buttonMultiply, 1, 2);
layout->addWidget(buttonDivide, 1, 3);
layout->addWidget(buttonClear, 2, 0, 1, 3);
layout->addWidget(buttonEqual, 2, 3);
mainWindow->setLayout(layout);
// 连接按钮的信号和槽
QObject::connect(buttonAdd, &QPushButton::clicked, [=]() {
double num = lineEdit->text().toDouble();
lineEdit->setText(QString::number(num + lineEdit->text().toDouble()));
});
QObject::connect(buttonSubtract, &QPushButton::clicked, [=]() {
double num = lineEdit->text().toDouble();
lineEdit->setText(QString::number(num - lineEdit->text().toDouble()));
});
QObject::connect(buttonMultiply, &QPushButton::clicked, [=]() {
double num = lineEdit->text().toDouble();
lineEdit->setText(QString::number(num * lineEdit->text().toDouble()));
});
QObject::connect(buttonDivide, &QPushButton::clicked, [=]() {
double num = lineEdit->text().toDouble();
if (num == 0) {
QMessageBox::warning(mainWindow, "警告", "除数不能为0");
return;
}
lineEdit->setText(QString::number(num / lineEdit->text().toDouble()));
});
QObject::connect(buttonClear, &QPushButton::clicked, [=]() {
lineEdit->clear();
});
QObject::connect(buttonEqual, &QPushButton::clicked, [=]() {
double num = lineEdit->text().toDouble();
lineEdit->setText(QString::number(num));
});
// 显示窗口
mainWindow->show();
return app.exec();
}
```
该程序使用了Qt的GUI库,创建了一个主窗口,并在窗口中添加了一个文本框和一些按钮,实现了简单的加、减、乘、除四则运算。当用户点击按钮时,程序会根据文本框中的数字进行相应的计算,并将结果显示在文本框中。这只是一个简单的Qt项目实例,如果您想了解更多关于Qt的内容,可以参考Qt官方文档或者其他的Qt教程。
阅读全文