用qt做一个计算器
时间: 2024-02-01 10:04:15 浏览: 167
用QT做的一个计算器
4星 · 用户满意度95%
下面是一个简单的用Qt实现的计算器示例,可以进行加、减、乘、除的计算:
```cpp
#include <QApplication>
#include <QWidget>
#include <QGridLayout>
#include <QLineEdit>
#include <QPushButton>
class Calculator : public QWidget
{
public:
Calculator(QWidget *parent = 0);
private slots:
void buttonClicked();
private:
QLineEdit *lineEdit;
QPushButton *buttons[16];
QGridLayout *gridLayout;
QString str;
};
Calculator::Calculator(QWidget *parent)
: QWidget(parent)
{
lineEdit = new QLineEdit(this);
lineEdit->setReadOnly(true);
lineEdit->setAlignment(Qt::AlignRight);
lineEdit->setMaxLength(15);
gridLayout = new QGridLayout(this);
gridLayout->addWidget(lineEdit, 0, 0, 1, 4);
for (int i = 0; i < 10; ++i) {
buttons[i] = new QPushButton(QString::number(i), this);
gridLayout->addWidget(buttons[i], (i + 3) / 3, (i - 1) % 3, 1, 1);
connect(buttons[i], SIGNAL(clicked()), this, SLOT(buttonClicked()));
}
buttons[10] = new QPushButton("+", this);
gridLayout->addWidget(buttons[10], 1, 3, 1, 1);
connect(buttons[10], SIGNAL(clicked()), this, SLOT(buttonClicked()));
buttons[11] = new QPushButton("-", this);
gridLayout->addWidget(buttons[11], 2, 3, 1, 1);
connect(buttons[11], SIGNAL(clicked()), this, SLOT(buttonClicked()));
buttons[12] = new QPushButton("*", this);
gridLayout->addWidget(buttons[12], 3, 3, 1, 1);
connect(buttons[12], SIGNAL(clicked()), this, SLOT(buttonClicked()));
buttons[13] = new QPushButton("/", this);
gridLayout->addWidget(buttons[13], 4, 3, 1, 1);
connect(buttons[13], SIGNAL(clicked()), this, SLOT(buttonClicked()));
buttons[14] = new QPushButton("C", this);
gridLayout->addWidget(buttons[14], 4, 0, 1, 1);
connect(buttons[14], SIGNAL(clicked()), lineEdit, SLOT(clear()));
buttons[15] = new QPushButton("=", this);
gridLayout->addWidget(buttons[15], 4, 2, 1, 1);
connect(buttons[15], SIGNAL(clicked()), this, SLOT(buttonClicked()));
setLayout(gridLayout);
}
void Calculator::buttonClicked()
{
QPushButton *button = qobject_cast<QPushButton *>(sender());
if (button) {
QString text = button->text();
if (text == "=") {
QString result = QString::number(eval(str));
lineEdit->setText(result);
str = "";
} else if (text == "C") {
lineEdit->clear();
str = "";
} else {
str += text;
lineEdit->setText(str);
}
}
}
int eval(QString str)
{
int n = str.length();
int op = '+', num = 0, ans = 0;
for (int i = 0; i < n; ++i) {
if (str[i].isDigit()) {
num = num * 10 + (str[i].toLatin1() - '0');
}
if (!str[i].isDigit() && !str[i].isSpace() || i == n - 1) {
if (op == '+') {
ans += num;
} else if (op == '-') {
ans -= num;
} else if (op == '*') {
ans *= num;
} else if (op == '/') {
ans /= num;
}
op = str[i].toLatin1();
num = 0;
}
}
return ans;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Calculator calculator;
calculator.show();
return app.exec();
}
```
这个计算器界面由一个QLineEdit和16个QPushButton组成。QPushButton是数字和运算符按钮,QLineEdit用于显示输入和结果。在buttonClicked()槽函数中,根据点击的按钮类型进行相应的处理。eval()函数用于实现表达式求值。
阅读全文