-
Notifications
You must be signed in to change notification settings - Fork 0
/
budgetUI.py
848 lines (718 loc) · 35.1 KB
/
budgetUI.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
from dataclasses import dataclass
from functools import partial
from pprint import pprint
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from PySide2 import QtWidgets, QtGui, QtCore
from matplotlib import pyplot
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
@dataclass
class BudgetData:
expense: str
allotted: float
spending: float
comment: str
class BudgetEditorWindow(QtWidgets.QMainWindow):
"""
This class is for managing general aspects of the UI window of a
budget app(not the tree widget and it's items)
"""
budget_added = QtCore.Signal(dict)
budget_removed = QtCore.Signal(dict)
budget_updated = QtCore.Signal(dict)
add_new_transaction_signal = QtCore.Signal(str, str, str, str)
del_transaction_signal = QtCore.Signal(dict)
del_row_signal = QtCore.Signal(str, str, str, str)
def __init__(self, budget):
super().__init__()
# User settings.
settings = QtCore.QSettings("EP", "BudgetApp")
self.restoreGeometry(settings.value("windowGeometry"))
self.restoreState(settings.value("windowState"))
# Initialize UI.
self.setWindowTitle('Budget Test')
self.setMinimumSize(1280, 720)
# Create a calendar widget
self.dateEdit = QtWidgets.QDateEdit(self)
self.dateEdit.setDisplayFormat('MMMM yyyy')
self.dateEdit.setDate(QtCore.QDate.currentDate())
self.dateEdit.setCalendarPopup(True)
self.dateEdit.calendarWidget().selectionChanged.connect(self.on_calendar_selection_changed)
self.transferBtn = QtWidgets.QPushButton('Transfer From Previous')
self.transferBtn.clicked.connect(self.transfer_from_previous_month)
# Create a QTreeWidget
self.tree = BudgetTreeWidget(self)
self.tree.setItemDelegate(BudgetItemDelegate(self.tree))
self.tree.setColumnCount(5)
self.tree.header().setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
self.tree.header().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
self.tree.header().setSectionResizeMode(0, QtWidgets.QHeaderView.Interactive)
self.tree.setHeaderLabels(
['Category', 'Expense', 'Allotted', 'Spending', 'Comment'])
# Connect the itemChanged signal to a slot
# self.tree.itemChanged.connect(self.set_cell_style)
self.figure, self.axes = pyplot.subplots()
# Create a FigureCanvasQTAgg object to display the figure
self.figure_canvas = FigureCanvasQTAgg(self.figure)
self.figure.set_facecolor("#AAAAAA")
# Create a button to save the table data to the loaded json file.
self.save_button = QtWidgets.QPushButton('Save')
self.save_button.clicked.connect(self.save_tree_data)
# Create a button to visualize the table data as a graph.
self.visualize_button = QtWidgets.QPushButton('Visualize graph')
self.visualize_button.clicked.connect(self.visualize_data)
self.add_transaction_button = QtWidgets.QPushButton('Add/Edit transaction')
self.add_transaction_button.clicked.connect(self.show_add_transaction_popup)
self.add_delete_button = QtWidgets.QPushButton('Delete')
self.add_delete_button.clicked.connect(self.delete_selected_row)
self.figure_canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.category_btn = QtWidgets.QPushButton('Add category')
main_layout = QtWidgets.QHBoxLayout()
layout = QtWidgets.QVBoxLayout()
dates_layout = QtWidgets.QHBoxLayout()
dates_layout.addWidget(self.dateEdit)
dates_layout.addWidget(self.transferBtn)
layout.addLayout(dates_layout)
layout.addWidget(self.tree)
button_layout = QtWidgets.QHBoxLayout()
button_layout.addWidget(self.save_button)
button_layout.addWidget(self.add_transaction_button)
button_layout.addWidget(self.add_delete_button)
button_layout.addWidget(self.visualize_button)
layout.addLayout(button_layout)
main_layout.addLayout(layout)
main_layout.addWidget(self.figure_canvas)
widget = QtWidgets.QWidget()
widget.setLayout(main_layout)
self.setCentralWidget(widget)
# Visualize current month as soon as the app loads.
# self.visualize_button.click()
set_dark_theme()
self.setStyleSheet("""
QPushButton{
border: 0;
background-color: #222222;
padding: 15px;
border-radius: 15px;
}
QPushButton::hover{
border: 2px solid;
border-color: #0492C2;
}
QPushButton::pressed{
background-color: #0492C2;
}
""")
self.budget = budget
# Signals for budget logic.
self.combo_category = None
self.combo_subcategory = None
#self.add_new_transaction_signal.connect(self.tree_update_spending)
'''
self.budget_added.connect(self.budget.add_budget)
self.budget_removed.connect(self.budget.remove_budget)
self.budget_updated.connect(self.budget.update_budget)
'''
def get_data_for_date(self,
input_year: str,
input_month: str,
disable_spending: bool = False,
disable_comment: bool = False) -> None:
""" Populates the tree widget with data from the json file.
:Example:
data = {"2023": {
... "January": {
... "Category 1": {
... "Expense 1": {
... "Allotted": 100,
... "Spending": 50,
... "Comment": "This is a comment"
... }
... }
... }
... }
...}
"""
self.tree.clear()
if self.budget.data.get(input_year) is None:
return None
if self.budget.data.get(input_year).get(input_month) is None:
return None
for category, category_data in self.budget.data[input_year][input_month].items():
category_item = BudgetCategoryItem(self.tree)
category_item.setText(0, category)
for expense, expenseData in category_data.items():
if disable_spending:
expenseData["Spending"] = 0
if disable_comment:
expenseData["Comment"] = ""
BudgetItem(category_item,
expense,
round(float(expenseData["Allotted"]), 2),
round(float(expenseData["Spending"]), 2),
expenseData["Comment"],
)
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
settings = QtCore.QSettings("EP", "BudgetApp")
settings.setValue("windowGeometry", self.saveGeometry())
settings.setValue("windowState", self.saveState())
super().closeEvent(event)
def on_calendar_selection_changed(self):
print(self.sender())
# Update the table data when the calendar selection changes
print(f'month : {self.dateEdit.calendarWidget().selectedDate().toString("yyyy")}')
print(f'month : {self.dateEdit.calendarWidget().selectedDate().toString("MMMM")}')
self.get_data_for_date(self.dateEdit.calendarWidget().selectedDate().toString("yyyy"),
self.dateEdit.calendarWidget().selectedDate().toString("MMMM"))
# self.set_table_data()
def transfer_from_previous_month(self):
current_date = self.dateEdit.calendarWidget().selectedDate()
previous_month_date = current_date.addMonths(-1)
self.get_data_for_date(previous_month_date.toString("yyyy"),
previous_month_date.toString("MMMM"),
disable_spending=True)
def save_tree_data(self):
# Get the selected month from the calendar widget
selected_year = self.dateEdit.calendarWidget().selectedDate().toString("yyyy")
selected_month = self.dateEdit.calendarWidget().selectedDate().toString("MMMM")
# Iterate over the tree and save the data
selected_month_data = {}
try:
original_month_data = self.budget.data[selected_year][selected_month]
selected_month_data = original_month_data
except KeyError as e:
print("Nothing to save")
iter_data = {key: value for key, value in original_month_data.items()
if not self.tree.find_category_item(key)}
for key in iter_data.keys():
self.del_row_signal.emit(selected_year,
selected_month,
key,
"")
iter_data_exp = {(key, key1) for key, value in original_month_data.items()
for key1 in value.keys()
if not self.tree.find_expense_item(key, key1)}
for key, key1 in iter_data_exp:
if not self.tree.find_expense_item(key, key1):
self.del_row_signal.emit(selected_year,
selected_month,
key,
key1)
# items = self.tree.findItems("", QtCore.Qt.MatchContains) if parent is None else parent.takeChildren()
for i in range(self.tree.topLevelItemCount()):
category_item = self.tree.topLevelItem(i)
for j in range(category_item.childCount()):
category_name = category_item.text(0)
expense_item = category_item.child(j)
expense = expense_item.text(1)
allotted = expense_item.text(2)
spending = expense_item.text(3)
comment = expense_item.text(4)
category_update = {
expense: {
"Allotted": allotted,
"Spending": spending,
"Comment": comment
}
}
if category_name in selected_month_data:
selected_month_data[category_name].update(category_update)
else:
selected_month_data[category_name] = category_update
self.budget.data[selected_year][selected_month] = selected_month_data
self.budget.save()
def show_add_transaction_popup(self):
popup = AddTransactionPopup(self, self.budget, self.dateEdit.calendarWidget().selectedDate().toString("yyyy"),
self.dateEdit.calendarWidget().selectedDate().toString("MMMM"))
def visualize_data(self):
# Get the selected month from the calendar widget
selectedYear = self.dateEdit.calendarWidget().selectedDate().toString('yyyy')
selectedMonth = self.dateEdit.calendarWidget().selectedDate().toString('MMMM')
# Filter the data to only include the selected month
data = self.budget.data.get(selectedYear).get(selectedMonth)
if data is None:
return
# Extract the category, expense, and spending data from the JSON data
categories = []
allotted = {}
spending = {}
amounts = []
types = []
overall = {}
overall.update({"Allotted": 0.0, "Spending": 0.0})
for category, subdict in data.items():
categories.append(category)
allotted.update({category: 0.0})
spending.update({category: 0.0})
for subcategory, values in subdict.items():
# expenses.append(subcategory)
allotted[category] += float(values['Allotted'])
# amounts.append(float(values['Allotted']))
# types.append('Allotted')
# expenses.append(subcategory)
spending[category] += float(values['Spending'])
# amounts.append(float(values['Spending']))
# types.append('Spending')
amounts.append(allotted[category])
overall["Allotted"] += allotted[category]
types.append('Allotted')
amounts.append(spending[category])
overall["Spending"] += spending[category]
types.append("Spending")
categories.append(category)
categories.append("Overall")
categories.append("Overall")
amounts.append(overall["Allotted"])
types.append('Allotted')
amounts.append(overall["Spending"])
types.append('Spending')
# Create a dataframe with the data
data = pd.DataFrame({'expenses': categories, 'amounts': amounts, 'types': types})
# Set the theme of the plot
sns.set_theme(style="whitegrid", palette="pastel", font_scale=1.2, color_codes=True)
# Create a bar chart with seaborn
self.axes.clear()
ax = sns.barplot(x="amounts", y="expenses", hue="types", data=data, ax=self.axes)
self.axes.set_title(f'{selectedMonth} Budget')
self.axes.set_xlabel('Amount')
self.axes.set_ylabel('Expense')
# Remove the top and right spines
sns.despine(offset=10)
# Adjust the spacing and padding
plt.tight_layout(pad=2.5)
# Add labels and numbers to the barplot
for container in ax.containers:
ax.bar_label(container, fmt='%.2f')
# Update the graph on the FigureCanvasQTAgg object
self.figure_canvas.draw()
def tree_update_spending(self, month_data):
self.tree.update_expense_spending(month_data)
def delete_selected_row(self):
selected_year = self.dateEdit.calendarWidget().selectedDate().toString("yyyy")
selected_month = self.dateEdit.calendarWidget().selectedDate().toString("MMMM")
self.tree.remove_currently_selected(selected_year, selected_month)
class AddTransactionPopup(QtWidgets.QDialog):
category_popup_closed = QtCore.Signal(str, str)
def __init__(self, parent, budget, year, month):
super().__init__(parent)
self.budget = budget
self.year = year
self.month = month
self.setWindowTitle("Add transaction")
self.setMinimumWidth(1000)
self.setMinimumHeight(200)
self.timer = QtCore.QTimer(self)
try:
self.year_data = self.budget.data[year]
except KeyError:
self.budget.data[year] = {}
self.year_data = self.budget.data[year]
try:
self.month_data = self.budget.data[year][month]
except KeyError:
self.budget.data[year][month] = {}
self.month_data = self.budget.data[year][month]
self.combo_category = QtWidgets.QComboBox(self)
self.combo_category.addItems(self.month_data)
self.combo_category.addItem("Add/Edit...")
self.combo_subcategory = QtWidgets.QComboBox(self)
self.combo_subcategory.setObjectName('combo_expense')
# activated signal triggers even when press the same item
# this is needed when the only option is "Add/Edit..."
self.combo_category.activated.connect(self.populate_subcategories)
self.combo_subcategory.activated.connect(self.add_new_category)
self.combo_category.setCurrentIndex(1)
self.category_popup_closed.connect(self.select_new_categories)
transaction_amount = QtWidgets.QLineEdit(self)
transaction_amount.setPlaceholderText("Enter amount")
transaction_comment = QtWidgets.QLineEdit(self)
transaction_comment.setPlaceholderText("Description...")
self.transactions_tree = QtWidgets.QTreeWidget()
self.transactions_tree.setColumnCount(4)
self.transactions_tree.setHeaderLabels(["category", "Expense", "Spending", "Comment"])
add_button = QtWidgets.QPushButton("Add", self)
add_button.clicked.connect(lambda: self.add_transaction(self.combo_category.currentText(),
self.combo_subcategory.currentText(),
transaction_amount.text(),
transaction_comment.text()))
delete_button = QtWidgets.QPushButton("Delete selected", self)
delete_button.clicked.connect(self.delete_transaction)
self.update_button = QtWidgets.QPushButton("Update budget", self)
self.update_button.clicked.connect(self.update_budget_with_transactions)
main_layout = QtWidgets.QVBoxLayout()
input_layout = QtWidgets.QHBoxLayout()
tree_layout = QtWidgets.QVBoxLayout()
input_layout.addWidget(self.combo_category)
input_layout.addWidget(self.combo_subcategory)
input_layout.addWidget(transaction_amount)
input_layout.addWidget(transaction_comment)
input_layout.addWidget(add_button)
input_layout.addWidget(delete_button)
tree_layout.addWidget(self.transactions_tree)
tree_layout.addWidget(self.update_button)
main_layout.addLayout(input_layout)
main_layout.addLayout(tree_layout)
self.setLayout(main_layout)
self.populate_rows()
self.exec_()
def add_new_category(self, sender=None):
# TODO: please fix the logic of this for a better one, it's easy
sender = self.sender() or sender
text = sender.currentText()
if text == "Add/Edit..." and sender == self.combo_category:
AddNewCategoryPopup(self)
elif text == "Add/Edit..." and sender == self.combo_subcategory:
category = self.combo_category.currentText()
if category == "Add/Edit...":
AddNewCategoryPopup(self)
else:
AddNewCategoryPopup(self, category)
def select_new_categories(self, *args):
category = args[0]
self.combo_category.addItem(category)
expense = args[1]
self.combo_subcategory.addItem(expense)
index_cat = self.combo_category.findText(category, QtCore.Qt.MatchFlag.MatchExactly)
index_exp = self.combo_subcategory.findText(expense, QtCore.Qt.MatchFlag.MatchExactly)
self.combo_category.setCurrentIndex(index_cat)
self.combo_subcategory.setCurrentIndex(index_exp)
def add_transaction(self, category, expense, amount, comment):
# Create a new QTreeWidgetItem with the data values
item = QtWidgets.QTreeWidgetItem([category, expense, str(amount), comment])
if expense == "":
print("Choose expense")
# Add the item to the tree widget
self.transactions_tree.addTopLevelItem(item)
# TODO: add transaction to budget_transactions
self.parent().add_new_transaction_signal.emit(category,
expense,
str(amount),
comment)
item.setData(0, QtCore.Qt.UserRole, "placeholder")
#self.budget.transactions.add_new_transaction(category, expense, str(amount), comment)
def delete_transaction(self):
transaction_item = self.transactions_tree.currentItem()
transaction_index = self.transactions_tree.indexOfTopLevelItem(transaction_item)
data = transaction_item.data(0, QtCore.Qt.UserRole)
if data == "placeholder":
# the budget has to be updated before any transaction can be deleted
print("Update the budget")
return
else:
self.transactions_tree.takeTopLevelItem(transaction_index)
self.parent().del_transaction_signal.emit(data)
def populate_subcategories(self):
#TODO : also clear the comboboxes if categories were deleted
if self.sender().currentText() == "Add/Edit...":
self.add_new_category(self.sender())
subcategories = self.month_data.get(self.combo_category.currentText())
if self.combo_subcategory and subcategories:
self.combo_subcategory.clear()
self.combo_subcategory.addItems(subcategories)
index = self.combo_subcategory.findText("Add/Edit...")
if index == -1:
self.combo_subcategory.insertItem(0, "Add/Edit...")
def populate_rows(self):
self.transactions_tree.clear()
for row, transaction in enumerate(self.budget.transactions):
item = QtWidgets.QTreeWidgetItem(
[transaction.category, transaction.expense, str(float(transaction.amount)), transaction.comment])
data = {"id": transaction.id,
"category": transaction.category,
"expense": transaction.expense,
"amount": transaction.amount,
"comment": transaction.comment}
self.transactions_tree.addTopLevelItem(item)
item.setData(0, QtCore.Qt.UserRole, data)
item.setText(0, item.text(0))
item.setText(1, item.text(1))
item.setText(2, item.text(2))
item.setText(3, item.text(3))
#item.setText(3, item.text(4))
def update_budget_with_transactions(self):
#updated_spending = float(0)
updated_spending = {}
for row in range(self.transactions_tree.topLevelItemCount()):
category = self.transactions_tree.topLevelItem(row).text(0)
updated_spending.update({category: {}})
for row in range(self.transactions_tree.topLevelItemCount()):
category = self.transactions_tree.topLevelItem(row).text(0)
expense = self.transactions_tree.topLevelItem(row).text(1)
for row1 in range(self.transactions_tree.topLevelItemCount()):
expense = self.transactions_tree.topLevelItem(row).text(1)
if self.transactions_tree.topLevelItem(row).text(0) == category:
updated_spending[category].update({expense: float(0)})
for row in range(self.transactions_tree.topLevelItemCount()):
category = self.transactions_tree.topLevelItem(row).text(0)
expense = self.transactions_tree.topLevelItem(row).text(1)
amount = self.transactions_tree.topLevelItem(row).text(2)
comment = self.transactions_tree.topLevelItem(row).text(3)
row_data = self.transactions_tree.topLevelItem(row).data(0, QtCore.Qt.UserRole)
updated_spending[category][expense] += float(amount)
# # TODO put this on logic module instead.
self.month_data[category][expense].update({"Spending": updated_spending[category][expense]})
self.parent().tree_update_spending(updated_spending)
self.populate_rows()
class AddNewCategoryPopup(QtWidgets.QDialog):
def __init__(self, parent, category: str = None):
super().__init__(parent)
self.budget = parent.budget
self.setWindowTitle("Add new category")
self.setMinimumWidth(1000)
self.category_name_line_edit = QtWidgets.QLineEdit(self)
self.category_name_line_edit.setPlaceholderText("Enter category name...")
self.category_name_line_edit.setText(category if category != 'Add new...' else None)
self.expense_name_line_edit = QtWidgets.QLineEdit(self)
self.expense_name_line_edit.setPlaceholderText("Enter expense name...")
self.allotted_amount_line_edit = QtWidgets.QLineEdit(self)
self.allotted_amount_line_edit.setPlaceholderText("Enter allotted amount...")
self.timer = QtCore.QTimer(self)
self.comment_line_edit = QtWidgets.QLineEdit(self)
self.comment_line_edit.setPlaceholderText("Enter comment...")
add_button = QtWidgets.QPushButton("Add", self)
add_button.clicked.connect(
lambda: self.add_new_category(self.category_name_line_edit.text(),
self.expense_name_line_edit.text(),
self.allotted_amount_line_edit.text(),
self.comment_line_edit.text()))
main_layout = QtWidgets.QVBoxLayout()
input_layout = QtWidgets.QHBoxLayout()
input_layout.addWidget(self.category_name_line_edit)
input_layout.addWidget(self.expense_name_line_edit)
input_layout.addWidget(self.allotted_amount_line_edit)
input_layout.addWidget(self.comment_line_edit)
input_layout.addWidget(add_button)
main_layout.addLayout(input_layout)
self.setLayout(main_layout)
self.exec_()
self.close()
self.destroy()
self.deleteLater()
def add_new_category(self, category, expense, allotted, comment):
# This block of code checks that we are not adding "empty"
# expense/category/allotted amount
style = self.category_name_line_edit.styleSheet()
if not category:
self.category_name_line_edit.setStyleSheet(StyleManager.red_frame_style)
self.timer.singleShot(1000, lambda: self.back_to_style(self.category_name_line_edit,
style, category))
return
if not expense:
self.expense_name_line_edit.setStyleSheet(StyleManager.red_frame_style)
self.timer.singleShot(1000, lambda: self.back_to_style(self.expense_name_line_edit,
style, expense))
return
if not allotted:
self.allotted_amount_line_edit.setStyleSheet(StyleManager.red_frame_style)
self.timer.singleShot(1000, lambda: self.back_to_style(self.allotted_amount_line_edit,
style, allotted))
return
try:
float(allotted)
except ValueError:
self.allotted_amount_line_edit.setStyleSheet(StyleManager.red_frame_style)
self.timer.singleShot(1000, lambda: self.back_to_style(self.allotted_amount_line_edit,
style, allotted))
return
# This part of the code checks if we already have the category created
# if we don't it will create a new
tree: QtWidgets.QTreeWidget = self.parent().parent().tree
category_item = tree.find_category_item(category)
if category_item is None:
category_item = BudgetCategoryItem(tree)
category_item.setText(0, category)
if comment is None:
comment = ""
# This part of the code checks if such expense item already exists
# if it does not it creates the expense if it does it updates
# allotted and comment
expense_item = tree.find_expense_item(category, expense)
if expense_item:
original_text = self.expense_name_line_edit.text()
style_expense = StyleManager.get_temp_text_style("Exists")
self.expense_name_line_edit.setStyleSheet(style_expense)
self.timer.singleShot(800, lambda: self.back_to_style(self.expense_name_line_edit,
style, original_text))
style_allotted = StyleManager.get_temp_text_style("Updated")
self.allotted_amount_line_edit.setStyleSheet(style_allotted)
self.timer.singleShot(800, lambda: self.back_to_style(self.allotted_amount_line_edit,
style, allotted))
self.comment_line_edit.setStyleSheet(style_allotted)
expense_item.setText(2, allotted)
self.timer.singleShot(800, lambda: self.back_to_style(self.comment_line_edit,
style, comment))
expense_item.setText(4, comment)
return
else:
expense_item = BudgetItem(category_item, expense, float(allotted), 0.0, comment)
self.budget.add_new_category(self.parent().year, self.parent().month,
category, expense, float(allotted), comment)
tree.expandItem(category_item)
self.parent().category_popup_closed.emit(category, expense)
self.close()
@staticmethod
def back_to_style(widget: QtWidgets.QLineEdit, style: str, text: str) -> None:
widget.setStyleSheet(style)
widget.setText(text)
# def closeEvent(self, event: QtGui.QCloseEvent) -> None:
# print("close event")
# category = self.category_name_line_edit.text()
# expense = self.expense_name_line_edit.text()
# self.parent().category_popup_closed.emit(category, expense)
class BudgetCategoryItem(QtWidgets.QTreeWidgetItem):
def __init__(self, parent=None):
super().__init__(parent)
class BudgetItem(QtWidgets.QTreeWidgetItem):
"""
Class to the set QTreeWidgetItem object for the new expense added by user
"""
def __init__(self, parent, expense: str, allotted: float, spending: float, comment: str):
super().__init__(parent)
self.setData(0, QtCore.Qt.UserRole, BudgetData(expense, allotted, spending, comment))
self.setText(1, expense)
self.setText(2, str(allotted))
self.setText(3, str(spending))
self.setText(4, comment)
if spending > allotted:
# print(f'spending {spending} > allotted {allotted}')
pass
else:
print(f'spending {spending} <= allotted {allotted}')
print(spending + 1, allotted + 1)
class BudgetItemDelegate(QtWidgets.QStyledItemDelegate):
"""
The class paint expense in red if the expense exceeds allotted
"""
def __init__(self, parent):
super().__init__(parent=parent)
def paint(self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> None:
option.backgroundBrush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
option.font.setBold(True)
option.rect.adjust(2.2, 2.2, -2.2, -2.2)
item = self.parent().itemFromIndex(index)
data = item.data(0, QtCore.Qt.UserRole)
if data is not None:
if data.spending > data.allotted:
painter.setPen(QtGui.QPen("red"))
painter.drawRect(option.rect)
else:
painter.setPen(QtGui.QPen("green"))
painter.drawRect(option.rect)
super().paint(painter, option, index)
class BudgetTreeWidget(QtWidgets.QTreeWidget):
"""
Class manages QTreeWidget and it's items of the YU
"""
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.setStyleSheet("""
QTreeWidget{
border: 0;
background-color: #222222;
}
QTreeWidget::item{
border: 0;
background-color: #222222;
background-color: #222222;
padding: 10px;
border-radius: 10px;
}
QTreeWidget::item:checked{
border: 2px solid;
border-color: #C29202;
background-color: #C29202;
}
QTreeWidget::item:selected{
background-color: #0492C2;
}
""")
def find_category_item(self, category: str) -> QtWidgets.QTreeWidgetItem:
category_item = None
for i in range(self.topLevelItemCount()):
if self.topLevelItem(i).text(0) == category:
category_item = self.topLevelItem(i)
break
return category_item
def find_expense_item(self, category: str, expense: str) -> QtWidgets.QTreeWidgetItem:
category_item = self.find_category_item(category)
if not category_item:
return None
expense_item = None
for i in range(0, category_item.childCount()):
if category_item.child(i).text(1) == expense:
expense_item = category_item.child(i)
return expense_item
def remove_currently_selected(self, year, month):
"""
Removes currently selected
"""
current_item = self.currentItem()
if current_item:
parent_item = current_item.parent()
if parent_item:
index = parent_item.indexOfChild(current_item)
category = parent_item.text(0)
removed_item = parent_item.takeChild(index)
self.parent.del_row_signal.emit(year,
month,
category,
removed_item.text(1))
del removed_item
else:
# It's a top-level item
index = self.indexOfTopLevelItem(current_item)
removed_item = self.takeTopLevelItem(index)
self.parent.del_row_signal.emit(year,
month,
removed_item.text(0),
None)
del removed_item
def update_expense_spending(self, data):
"""
data passed to this method(slot) by the add_new_transaction_signal
Signal of the parent BudgetEditorWindow: str
"""
print(data)
for key, value in data.items():
for key1, value1 in value.items():
tree_item = self.find_expense_item(key, key1)
tree_item.setText(3, str(value1))
class StyleManager:
default_style = ""
red_frame_style = """
QLineEdit {
border: 2px solid red;
border-radius: 4px;
padding: 2px;
}
"""
@staticmethod
def get_temp_text_style(message: str) -> str:
temp_text_style = """
QLineEdit {{
color: red;
qproperty-text: "{}";
text-align: right;
}}
""".format(message)
return temp_text_style
def set_dark_theme():
# Set the dark theme
dark_palette = QtGui.QPalette()
dark_palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53, 53, 53))
dark_palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(255, 255, 255))
dark_palette.setColor(QtGui.QPalette.Base, QtGui.QColor(25, 25, 25))
dark_palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53, 53, 53))
dark_palette.setColor(QtGui.QPalette.ToolTipBase, QtGui.QColor(255, 255, 255))
dark_palette.setColor(QtGui.QPalette.ToolTipText, QtGui.QColor(255, 255, 255))
dark_palette.setColor(QtGui.QPalette.Text, QtGui.QColor(255, 255, 255))
dark_palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53))
dark_palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor(255, 255, 255))
dark_palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)
dark_palette.setColor(QtGui.QPalette.Link, QtGui.QColor(42, 130, 218))
dark_palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(42, 130, 218))
dark_palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)
QtWidgets.QApplication.setPalette(dark_palette)
QtWidgets.QApplication.setStyle('Fusion')