-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
260 lines (203 loc) · 8.55 KB
/
main.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import sys
import config
from typing import Union, Optional
from operator import add, sub, mul, truediv
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtGui import QFontDatabase
from design import Ui_MainWindow
operations = {
'+': add,
'-': sub,
'×': mul,
'/': truediv
}
class Calculator(QMainWindow):
def __init__(self):
super(Calculator, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowTitle("OneCalculator")
self.entry = self.ui.le_entry
self.temp = self.ui.lbl_temp
self.entry_max_len = self.entry.maxLength()
QFontDatabase.addApplicationFont("ui/fonts/Intro.ttf")
for btn in config.DIGIT_BUTTONS:
getattr(self.ui, btn).clicked.connect(self.add_digit)
self.ui.btn_calc.clicked.connect(self.calculate)
for btn in config.MATH_OPERATIONS:
getattr(self.ui, btn).clicked.connect(self.math_operation)
self.ui.btn_clear.clicked.connect(self.clear_all)
self.ui.btn_ce.clicked.connect(self.clear_entry)
self.ui.btn_point.clicked.connect(self.add_point)
self.ui.btn_sub.clicked.connect(self.negate)
self.ui.btn_backspace.clicked.connect(self.backspace)
def add_digit(self) -> None:
self.remove_error()
self.clear_temp_if_equality()
btn = self.sender()
if btn.objectName() in config.DIGIT_BUTTONS:
if self.entry.text() == '0':
self.entry.setText(btn.text())
else:
self.entry.setText(self.entry.text() + btn.text())
self.adjust_entry_font_size()
def add_point(self) -> None:
self.clear_temp_if_equality()
if '.' not in self.entry.text():
self.entry.setText(self.entry.text() + '.')
self.adjust_entry_font_size()
def avoid_deleting_char_on_negation(self, entry: str) -> None:
if len(entry) == self.entry_max_len + 1 and '-' in entry:
self.entry.setMaxLength(self.entry_max_len + 1)
else:
self.entry.setMaxLength(self.entry_max_len)
def negate(self) -> None:
self.clear_temp_if_equality()
entry = self.ui.le_entry.text()
if '-' not in entry:
if entry != '0':
entry = '-' + entry
else:
entry = entry[1:]
self.avoid_deleting_char_on_negation(entry)
self.entry.setText(entry)
self.adjust_entry_font_size()
def backspace(self) -> None:
self.remove_error()
self.clear_temp_if_equality()
entry = self.entry.text()
if len(entry) != 1:
if len(entry) == 2 and '-' in entry:
self.entry.setText('0')
else:
self.entry.setText(entry[:-1])
else:
self.entry.setText('0')
self.adjust_entry_font_size()
def clear_all(self) -> None:
self.remove_error()
self.entry.setText('0')
self.adjust_entry_font_size()
self.temp.clear()
self.adjust_temp_font_size()
def clear_entry(self) -> None:
self.remove_error()
self.clear_temp_if_equality()
self.entry.setText('0')
self.adjust_entry_font_size()
def clear_temp_if_equality(self) -> None:
if self.get_math_sign() == '=':
self.temp.clear()
self.adjust_temp_font_size()
@staticmethod
def remove_trailing_zeros(num: Union[float, int, str]) -> str:
n = str(float(num))
return n.replace('.0', '') if n.endswith('.0') else n
def add_temp(self) -> None:
btn = self.sender()
entry = self.remove_trailing_zeros(self.entry.text())
if not self.temp.text() or self.get_math_sign() == '=':
self.ui.lbl_temp.setText(self.ui.le_entry.text() + f' {btn.text()} ')
self.adjust_temp_font_size()
self.entry.setText('0')
self.adjust_entry_font_size()
def get_entry_num(self) -> Union[int, float]:
entry = self.entry.text().strip('.')
return float(entry) if '.' in entry else int(entry)
def get_temp_num(self) -> Union[int, float, None]:
if self.temp.text():
temp = self.temp.text().strip('.').split()[0]
return float(temp) if '.' in temp else int(temp)
def get_math_sign(self) -> Optional[str]:
if self.temp.text():
return self.temp.text().strip('.').split()[-1]
def get_entry_text_width(self) -> int:
return self.entry.fontMetrics().boundingRect(self.entry.text()).width()
def get_temp_text_width(self) -> int:
return self.temp.fontMetrics().boundingRect(self.temp.text()).width()
def calculate(self) -> Optional[str]:
try:
result = self.remove_trailing_zeros(
(operations[self.get_math_sign()](self.get_temp_num(), self.get_entry_num())))
self.temp.setText(self.temp.text() + self.remove_trailing_zeros(self.entry.text()) + ' =')
self.adjust_temp_font_size()
self.entry.setText(result)
self.adjust_entry_font_size()
return result
except KeyError:
pass
except ZeroDivisionError:
self.show_zero_division_error()
def show_zero_division_error(self) -> None:
if self.get_temp_num() == 0:
self.show_error(config.ERROR_UNDEFINED)
else:
self.show_error(config.ERROR_ZERO_DIV)
def math_operation(self) -> None:
btn = self.sender()
if not self.temp.text():
self.add_temp()
else:
if self.get_math_sign() != btn.text():
if self.get_math_sign() == '=':
self.add_temp()
else:
self.replace_temp_sign()
else:
try:
self.temp.setText(self.calculate() + f' {btn.text()} ')
except TypeError:
pass
self.adjust_temp_font_size()
def replace_temp_sign(self) -> None:
btn = self.sender()
self.temp.setText(self.temp.text()[:-2] + f'{btn.text()} ')
def show_error(self, text: str) -> None:
self.entry.setMaxLength(len(text))
self.entry.setText(text)
self.adjust_entry_font_size()
self.disable_buttons(True)
def remove_error(self) -> None:
if self.entry.text() in (config.ERROR_UNDEFINED, config.ERROR_ZERO_DIV):
self.entry.setMaxLength(self.entry_max_len)
self.entry.setText('0')
self.adjust_entry_font_size()
self.disable_buttons(False)
def disable_buttons(self, disable: bool) -> None:
for btn in config.BUTTONS_TO_DISABLE:
getattr(self.ui, btn).setDisabled(disable)
color = 'color: #E6E6E6;' if disable else 'color: white;'
self.change_buttons_color(color)
def change_buttons_color(self, css_color: str) -> None:
for btn in config.BUTTONS_TO_DISABLE:
getattr(self.ui, btn).setStyleSheet(css_color)
def adjust_entry_font_size(self) -> None:
font_size = config.DEFAULT_ENTRY_FONT_SIZE
while self.get_entry_text_width() > self.entry.width() - 15:
font_size -= 1
self.entry.setStyleSheet(f'font-size: {font_size}pt; border: none;')
font_size = 1
while self.get_entry_text_width() < self.entry.width() - 60:
font_size += 1
if font_size > config.DEFAULT_ENTRY_FONT_SIZE:
break
self.entry.setStyleSheet(f'font-size: {font_size}pt; border: none;')
def adjust_temp_font_size(self) -> None:
font_size = config.DEFAULT_FONT_SIZE
while self.get_temp_text_width() > self.temp.width() - 10:
font_size -= 1
self.temp.setStyleSheet(f'font-size: {font_size}pt; color: #E6E6E6;')
font_size = 1
while self.get_temp_text_width() < self.temp.width() - 60:
font_size += 1
if font_size > config.DEFAULT_FONT_SIZE:
break
self.temp.setStyleSheet(f'font-size: {font_size}pt; color: #E6E6E6;')
def resizeEvent(self, event) -> None:
self.adjust_entry_font_size()
self.adjust_temp_font_size()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Calculator()
window.show()
sys.exit(app.exec())