This repository has been archived on 2024-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
justhomework/SoftwareDesign/Code/2-2-5_enhanced/mainwindow.cpp

95 lines
2.5 KiB
C++
Raw Normal View History

2022-03-29 08:42:01 +00:00
#include "mainwindow.h"
#include "cal.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
static QString displayText;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
ui->lineEdit->setText("0");
result = 0.0;
waitForOperand = true;
connectSlots();
}
MainWindow::~MainWindow() { delete ui; }
//错误处理
void MainWindow::abortOperation() {
result = 0.0;
pendingOperator.clear();
ui->lineEdit->setText("0");
waitForOperand = true;
QMessageBox::warning(this, "运算错误", "除数不能为零");
}
//数字被点击
void MainWindow::digitClicked() {
QPushButton *digitBtn = static_cast<QPushButton *>(sender());
// if(ui->lineEdit->text() == "0" && value == "0")
// return;
if (!isFinished) {
displayText.append(digitBtn->text());
ui->lineEdit->setText(displayText);
} else {
return;
}
}
void MainWindow::on_clearBtn_clicked() {
//将当前显示的数归零
displayText.chop(1);
ui->lineEdit->setText(displayText);
isFinished = false;
}
void MainWindow::on_clearAllBtn_clicked() {
//将当前显示的数据归零,并将之前保存的数据运算清除
displayText.clear();
ui->lineEdit->setText(displayText);
isFinished = false;
result = 0.0;
}
void MainWindow::on_equalBtn_clicked() {
result = cal(displayText.toStdString());
isFinished = 1;
ui->lineEdit->setText(QString::number(result));
}
//运算符
void MainWindow::operatorClicked() {
QPushButton *clickedBtn = qobject_cast<QPushButton *>(sender());
if (!isFinished) {
displayText.append(clickedBtn->text());
ui->lineEdit->setText(displayText);
} else {
return;
}
}
//槽链接
void MainWindow::connectSlots() {
QPushButton *digitBtns[10] = {ui->digitBtn0, ui->digitBtn1, ui->digitBtn2,
ui->digitBtn3, ui->digitBtn4, ui->digitBtn5,
ui->digitBtn6, ui->digitBtn7, ui->digitBtn8,
ui->digitBtn9};
for (auto btn : digitBtns)
connect(btn, &QPushButton::clicked, this, &MainWindow::digitClicked);
QPushButton *operatorBtns[6] = {ui->addBtn, ui->subtractionBtn,
ui->mulBtn, ui->divisionBtn,
ui->squareBtn, ui->pointBtn};
for (auto btn : operatorBtns)
connect(btn, &QPushButton::clicked, this, &MainWindow::operatorClicked);
}
//没用的函数,让它能编译成功
void MainWindow::on_squareBtn_clicked() {}
void MainWindow::on_pointBtn_clicked() {}
void MainWindow::on_signBtn_clicked() {}