-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculatedialog.cpp
More file actions
105 lines (78 loc) · 2.56 KB
/
calculatedialog.cpp
File metadata and controls
105 lines (78 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "calculatedialog.h"
#include "ui_calculatedialog.h"
#include <QMessageBox>
CalculateDialog::CalculateDialog(const Expr& e,QWidget *parent)
: QDialog(parent)
, ui(new Ui::EvaluateDialog)
{
ui->setupUi(this);
expression = e;
ui->lineEdit->setText(e.toInfix());
initTable();
}
CalculateDialog::~CalculateDialog()
{
delete ui;
}
void CalculateDialog::initTable()
{
ui->tableWidget->setRowCount(0);
for(auto it = expression.varMap.begin(); it != expression.varMap.end(); it++)
{
char varName = it->first;
int varValue = (it->second = 0);
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
QTableWidgetItem *keyItem = new QTableWidgetItem(QString(QChar(varName)));
keyItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
ui->tableWidget->setItem(row, 0, keyItem);
QTableWidgetItem *valItem = new QTableWidgetItem(QString::number(varValue));
valItem->setBackground(QColor(Qt::transparent));
ui->tableWidget->setItem(row, 1 , valItem);
}
}
void CalculateDialog::on_calculateButton_clicked()
{
int rows = ui->tableWidget->rowCount();
bool allOk = true;
for (int i = 0; i < rows; ++i) {
QString keyStr = ui->tableWidget->item(i, 0)->text();
if (keyStr.isEmpty()) continue;
char key = keyStr.at(0).toLatin1();
QString valStr = ui->tableWidget->item(i, 1)->text();
bool ok;
double value = valStr.toDouble(&ok);
if (ok) {
expression.setVarValue(key, value);
ui->tableWidget->item(i, 1)->setBackground(Qt::transparent);
} else {
allOk = false;
ui->tableWidget->item(i, 1)->setBackground(QColor(255, 200, 200));
}
}
if (!allOk) {
QMessageBox::warning(this, "输入错误", "表格中包含非法的数字格式,请检查!");
return;
}
double result = expression.value();
ui->lineEdit->clear();
ui->label->clear();
ui->label->setText("求值:");
ui->lineEdit->setText(QString::number(result));
}
void CalculateDialog::on_resetButton_clicked()
{
ui->label->clear();
ui->label->setText("中缀表达式:");
ui->lineEdit->clear();
ui->lineEdit->setText(expression.toInfix());
int rows = ui->tableWidget->rowCount();
for(int i = 0; i < rows; ++i)
{
QTableWidgetItem *item = ui->tableWidget->item(i, 1);
if(item) {
item->setText("0");
item->setBackground(QColor(Qt::transparent));
}
}
}