用qt设计计算器,每行代码加注释
时间: 2024-05-11 12:19:09 浏览: 108
以下是用Qt设计计算器的代码,每行都附有注释解释代码的作用:
```c++
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 连接数字按钮的信号与槽
connect(ui->pushButton_0, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_1, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_3, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_4, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_5, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_6, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_7, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_8, SIGNAL(clicked()), this, SLOT(digitClicked()));
connect(ui->pushButton_9, SIGNAL(clicked()), this, SLOT(digitClicked()));
// 连接运算符按钮的信号与槽
connect(ui->pushButton_add, SIGNAL(clicked()), this, SLOT(operatorClicked()));
connect(ui->pushButton_sub, SIGNAL(clicked()), this, SLOT(operatorClicked()));
connect(ui->pushButton_mul, SIGNAL(clicked()), this, SLOT(operatorClicked()));
connect(ui->pushButton_div, SIGNAL(clicked()), this, SLOT(operatorClicked()));
// 连接等号和归零按钮的信号与槽
connect(ui->pushButton_eq, SIGNAL(clicked()), this, SLOT(equalClicked()));
connect(ui->pushButton_clr, SIGNAL(clicked()), this, SLOT(clearClicked()));
// 初始化运算符和操作数
operatorClicked();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::digitClicked()
{
// 获取被点击的数字按钮对象
QPushButton *digitButton = qobject_cast<QPushButton *>(sender());
// 获取按钮上显示的数字
int digitValue = digitButton->text().toInt();
// 获取当前文本框中的数字
int currentValue = ui->lineEdit->text().toInt();
// 将按钮上的数字添加到当前文本框中的数字
int newValue = currentValue * 10 + digitValue;
// 更新文本框中的数字
ui->lineEdit->setText(QString::number(newValue));
}
void MainWindow::operatorClicked()
{
// 获取被点击的运算符按钮对象
QPushButton *operatorButton = qobject_cast<QPushButton *>(sender());
// 获取按钮上的运算符
QString operatorValue = operatorButton->text();
// 获取当前文本框中的数字
int currentValue = ui->lineEdit->text().toInt();
// 如果当前文本框中没有数字,则将操作数设为0
if (m_firstOperand.isNull()) {
m_firstOperand = currentValue;
}
// 记录运算符
m_operator = operatorValue;
// 清空文本框,等待输入第二个操作数
ui->lineEdit->clear();
}
void MainWindow::equalClicked()
{
// 获取当前文本框中的数字
int currentValue = ui->lineEdit->text().toInt();
// 如果当前文本框中没有数字,则将操作数设为0
if (m_firstOperand.isNull()) {
m_firstOperand = currentValue;
}
// 根据运算符计算结果
if (m_operator == "+") {
m_result = m_firstOperand + currentValue;
} else if (m_operator == "-") {
m_result = m_firstOperand - currentValue;
} else if (m_operator == "*") {
m_result = m_firstOperand * currentValue;
} else if (m_operator == "/")
阅读全文