如何用QT,做一个计算器,有加减乘除,退格,清除功能
时间: 2024-04-17 20:23:50 浏览: 126
您可以使用QT进行开发,以下是一个简单的示例代码,实现了一个基本的计算器界面,包括加减乘除,退格和清除功能:
```cpp
#include <QApplication>
#include <QWidget>
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
class Calculator : public QWidget
{
Q_OBJECT
public:
Calculator(QWidget *parent = nullptr) : QWidget(parent)
{
// 设置窗口标题
setWindowTitle("Calculator");
// 创建布局
QGridLayout *layout = new QGridLayout(this);
// 创建显示结果的文本框
resultLineEdit = new QLineEdit(this);
resultLineEdit->setReadOnly(true);
layout->addWidget(resultLineEdit, 0, 0, 1, 4);
// 创建数字按钮
for (int i = 0; i < 10; i++) {
buttons[i] = new QPushButton(QString::number(i), this);
layout->addWidget(buttons[i], (i+3)/3, (i-1)%3);
connect(buttons[i], &QPushButton::clicked, this, &Calculator::numberClicked);
}
// 创建操作符按钮
addButton = createOperatorButton("+");
subtractButton = createOperatorButton("-");
multiplyButton = createOperatorButton("*");
divideButton = createOperatorButton("/");
layout->addWidget(addButton, 1, 3);
layout->addWidget(subtractButton, 2, 3);
layout->addWidget(multiplyButton, 3, 3);
layout->addWidget(divideButton, 4, 3);
// 创建退格和清除按钮
backspaceButton = new QPushButton("Backspace", this);
clearButton = new QPushButton("Clear", this);
layout->addWidget(backspaceButton, 1, 0, 1, 2);
layout->addWidget(clearButton, 2, 0, 1, 2);
connect(backspaceButton, &QPushButton::clicked, this, &Calculator::backspaceClicked);
connect(clearButton, &QPushButton::clicked, this, &Calculator::clearClicked);
}
public slots:
void numberClicked()
{
QPushButton *button = qobject_cast<QPushButton*>(sender());
if (button) {
resultLineEdit->setText(resultLineEdit->text() + button->text());
}
}
void backspaceClicked()
{
QString text = resultLineEdit->text();
if (!text.isEmpty()) {
text.chop(1);
resultLineEdit->setText(text);
}
}
void clearClicked()
{
resultLineEdit->clear();
}
private:
QPushButton* createOperatorButton(const QString &text)
{
QPushButton *button = new QPushButton(text, this);
connect(button, &QPushButton::clicked, this, &Calculator::operatorClicked);
return button;
}
void operatorClicked()
{
QPushButton *button = qobject_cast<QPushButton*>(sender());
if (button) {
resultLineEdit->setText(resultLineEdit->text() + " " + button->text() + " ");
}
}
private:
QLineEdit *resultLineEdit;
QPushButton *buttons[10];
QPushButton *addButton;
QPushButton *subtractButton;
QPushButton *multiplyButton;
QPushButton *divideButton;
QPushButton *backspaceButton;
QPushButton *clearButton;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Calculator calculator;
calculator.show();
return a.exec();
}
#include "main.moc"
```
这是一个简单的计算器示例,使用了QT的QGridLayout布局来安排按钮和文本框的位置。每个数字按钮都连接了相应的槽函数,当按钮被点击时,数字将显示在文本框中。操作符按钮连接了一个槽函数,当按钮被点击时,相应的操作符将添加到文本框中。退格和清除按钮也有各自的槽函数,用于实现退格和清除功能。
请注意,这只是一个基本示例,仅包含了简单的加减乘除、退格和清除功能。您可以根据自己的需求进行扩展和修改。希望对您有帮助!
阅读全文