-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToDoPS6.py
More file actions
766 lines (651 loc) · 27.8 KB
/
Copy pathToDoPS6.py
File metadata and controls
766 lines (651 loc) · 27.8 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
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
'''
Small Utility to track ToDo Items using PySide6
https://github.com/matmuc/ToDoPy
Copyright (C) 2024 Matthias Vogt
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation version 3
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
'''
import json
import datetime
import sys, io, re
from os.path import exists
from PySide6.QtCore import Qt, QAbstractTableModel, QDate
from PySide6.QtGui import QBrush, QGuiApplication, QFont, QAction, QKeySequence, QShortcut
from PySide6.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, \
QVBoxLayout, QHBoxLayout, QCheckBox, QLabel, QTableView, QComboBox, QHeaderView, QSizePolicy, QSpacerItem, \
QDialog, QLineEdit, QDateEdit, QTextEdit, QStyle, QMenu
showDone = False
StatusFilter = 'Open'
CatSel = 'ALL'
def qDateFromStr(dStr):
try:
tmpD = datetime.datetime.strptime(dStr, '%Y-%m-%d')
qDate = QDate(tmpD.year, tmpD.month, tmpD.day)
return qDate
except:
return None
def qDateToDateStr(qDate):
if qDate.month() == 1 and qDate.year() == 2000 and qDate.day() == 1:
return ""
date = datetime.datetime(qDate.year(), qDate.month(), qDate.day())
return date.strftime("%Y-%m-%d")
def cleanString(strIn):
strOut = re.sub(r"[\n\r\t ]"," ",strIn)
strOut = re.sub(r"[ ]{2,}", " ", strOut)
return strOut
def getFilteredItems():
global showDone
global StatusFilter
global CatSel
filteredItems=[]
for item in ItemsObject:
if item['Status'].lower() == "deleted":
itemDeleted = True
else:
itemDeleted = False
if item['Status'].lower() == "done" or item['Status'].lower() == "obsolet":
itemDone = True
else:
itemDone = False
if CatSel == "ALL" or item['Category'] == CatSel:
itemCat = True
else:
itemCat = False
if StatusFilter == "Deleted":
if itemDeleted and itemCat:
filteredItems.append(item)
elif StatusFilter == "Done":
if itemDone and itemCat and not itemDeleted:
filteredItems.append(item)
elif StatusFilter == "All":
if not itemDeleted and itemCat:
filteredItems.append(item)
else:
if not itemDone and itemCat and not itemDeleted:
filteredItems.append(item)
#if (showDone and itemDone) or (not showDone and not itemDone) and not itemDeleted and itemCat:
# filteredItems.append(item)
return filteredItems
class TableModel(QAbstractTableModel):
def __init__(self):
super(TableModel, self).__init__()
self.filteredItems = getFilteredItems()
#print(self.filteredItems)
self.columns= { 0: 'Category', 1: 'Priority', 2: 'Status', 3: 'Title', 4: 'Description', 5: 'Date', 6: 'DueDate', 7: 'DoneDate'}
def data(self, index, role):
global showDone
global darkScheme
item = self.filteredItems[index.row()]
if item['Status'].lower() == "done":
itemDone = True
else:
itemDone = False
urgent = False
overdue = False
font = QFont('Arial',10)
font.setBold(False)
font.setItalic(False)
try:
itemdate = datetime.datetime.strptime(item['DueDate'],'%Y-%m-%d').date()
today = datetime.date.today()
deltaDays = (today-itemdate).days
if deltaDays > 0 and not itemDone:
overdue = True
elif deltaDays > - 7 and not itemDone:
urgent = True
except:
None
if role == Qt.DisplayRole:
text = item[self.columns[index.column()]]
#if index.column() == 1: # titel
# text = ' '+text+' '
return text
elif role == Qt.FontRole:
return font
#if not darkScheme:
# return QBrush('#000')
elif role == Qt.ForegroundRole:
if darkScheme:
return QBrush('#000')
else:
return QBrush('#000')
elif role == Qt.BackgroundRole:
if index.row()%2 == 0:
if darkScheme:
col = QBrush('#4452ac')
else:
col = QBrush('#f2f2ff')
else:
if darkScheme:
col = QBrush('#ddd')
else:
col = QBrush('#fff')
if overdue and not itemDone:
return QBrush('#f9c090') # red: '#f9c795'
elif urgent and not itemDone:
return QBrush('#f9f995') # yellow: '#f9f995'
else:
return col
def rowCount(self, index):
return len(self.filteredItems)
def columnCount(self, index):
return len(self.columns)
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.columns[section]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
#print("get Vertical "+str(section)+": "+str(self.filteredItems[section]['ID'])+" "+self.filteredItems[section]['Title'])
return f"{self.filteredItems[section]['ID']}"
class EditDialog(QDialog):
item = None
def __init__(self, item):
global categories
global statusList
super().__init__()
self.item = item
self.setWindowTitle("Edit Todo "+item['Title'])
self.setMinimumSize(800,100)
self.mainLayout = QVBoxLayout()
self.setLayout(self.mainLayout)
#self.setAttribute(QWA_DeleteOnClose)
titLayout = QHBoxLayout()
self.mainLayout.addLayout(titLayout)
self.catSelCB = QComboBox()
self.catSelCB.addItems(categories)
self.catSelCB.setCurrentText(item['Category'])
def onSelCategoryCB():
print (self.catSelCB.currentText())
newCatEdit.setText("")
self.catSelCB.currentTextChanged.connect(onSelCategoryCB)
titLayout.addWidget(self.catSelCB)
titLayout.addWidget(QLabel("New Category:"))
def onNewCat():
newItem = newCatEdit.text()
if len(newItem):
if not newItem in categories:
self.catSelCB.addItem(newItem)
self.catSelCB.setCurrentText(newItem)
newCatEdit.setText("")
newCatEdit = QLineEdit('', parent=self)
titLayout.addWidget(newCatEdit)
newCatEdit.setMaximumWidth(80)
newCatEdit.editingFinished.connect(onNewCat)
titLayout.addWidget(QLabel("Title"))
self.titleEdit = QLineEdit(item['Title'], parent=self)
titLayout.addWidget(self.titleEdit)
descLayout = QHBoxLayout()
descLayout.addWidget(QLabel("Description"))
self.descriptionEdit = QLineEdit(item['Description'], parent=self)
descLayout.addWidget(self.descriptionEdit)
self.mainLayout.addLayout(descLayout)
prioLayout = QHBoxLayout()
prioLayout.addWidget(QLabel("Priority"))
self.prioEdit = QLineEdit(item['Priority'], parent=self)
self.prioEdit.setMaximumWidth(50)
prioLayout.addWidget(self.prioEdit)
self.mainLayout.addLayout(prioLayout)
#statusLayout = QHBoxLayout()
prioLayout.addWidget(QLabel("Status"))
self.statusEdit = QLineEdit(item['Status'], parent=self)
self.statusEdit.setMaximumWidth(120)
prioLayout.addWidget(self.statusEdit)
self.statSelCB = QComboBox()
self.statSelCB.setMaximumWidth(120)
self.statSelCB.addItems(statusList)
self.statSelCB.setCurrentText(item['Status'])
def onSelStatusCB():
print("Sel Status: ",self.statSelCB.currentText())
self.statusEdit.setText(self.statSelCB.currentText())
self.statSelCB.currentTextChanged.connect(onSelStatusCB)
prioLayout.addWidget(self.statSelCB)
prioSpacer = QSpacerItem(800, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
prioLayout.addItem(prioSpacer)
#self.mainLayout.addLayout(statusLayout)
dateLayout = QHBoxLayout()
dlabel = QLabel("Date")
dlabel.setAlignment(Qt.AlignRight)
dateLayout.addWidget(dlabel)
self.dateEdit = QDateEdit()
self.dateEdit.setCalendarPopup(True)
self.dateEdit.setDisplayFormat("dd.MM.yyyy")
self.dateEdit.setDate(qDateFromStr(item['Date']))
dateLayout.addWidget(self.dateEdit)
dulabel = QLabel("DueDate")
dulabel.setAlignment(Qt.AlignRight)
dateLayout.addWidget(dulabel)
self.dueDateEdit = QDateEdit()
self.dueDateEdit.setCalendarPopup(True)
self.dueDateEdit.setDisplayFormat("dd.MM.yyyy")
self.dueDateEdit.setDate(qDateFromStr(item['DueDate']))
dateLayout.addWidget(self.dueDateEdit)
def onCDuBtn():
self.dueDateEdit.setDate(qDateFromStr('2000-01-01'))
def onDud3Btn():
ddDate = datetime.date.today() + datetime.timedelta(days=3)
self.dueDateEdit.setDate(qDateFromStr(ddDate.strftime("%Y-%m-%d")))
clearDuDButton = QPushButton(self.tr("X"), default=False, autoDefault=False)
clearDuDButton.setMaximumWidth(30)
clearDuDButton.pressed.connect(onCDuBtn)
dateLayout.addWidget(clearDuDButton)
p3dBtn = QPushButton(self.tr("+3"), default=False, autoDefault=False)
p3dBtn.setMaximumWidth(30)
p3dBtn.pressed.connect(onDud3Btn)
dateLayout.addWidget(p3dBtn)
dolabel = QLabel("DoneDate")
dolabel.setAlignment(Qt.AlignRight)
dateLayout.addWidget(dolabel)
self.doneDateEdit = QDateEdit()
self.doneDateEdit.setCalendarPopup(True)
self.doneDateEdit.setDisplayFormat("dd.MM.yyyy")
self.doneDateEdit.setDate(qDateFromStr(item['DoneDate']))
dateLayout.addWidget(self.doneDateEdit)
def onCDoBtn():
self.doneDateEdit.setDate(qDateFromStr('2000-01-01'))
clearDoDButton = QPushButton(self.tr("X"), default=False, autoDefault=False)
clearDoDButton.setMaximumWidth(30)
clearDoDButton.pressed.connect(onCDoBtn)
dateLayout.addWidget(clearDoDButton)
def onDoNowBtn():
self.doneDateEdit.setDate(qDateFromStr(datetime.date.today().strftime("%Y-%m-%d")))
doDNowButton = QPushButton(self.tr("NOW"), default=False, autoDefault=False)
doDNowButton.setMaximumWidth(37)
doDNowButton.pressed.connect(onDoNowBtn)
dateLayout.addWidget(doDNowButton)
self.mainLayout.addLayout(dateLayout)
self.progTextEdit = QTextEdit()
addProgLayout = QHBoxLayout()
self.mainLayout.addLayout(addProgLayout)
addProgLayout.addWidget(QLabel("Add new Progress"))
self.addProgEdit = QLineEdit('', parent=self)
self.addProgEdit.editingFinished.connect(self.onAddProg)
addProgLayout.addWidget(self.addProgEdit)
self.mainLayout.addWidget(self.progTextEdit)
for line in item['Progress']:
self.progTextEdit.append(line)
doneButton = QPushButton(self.tr("&Done"), default=False, autoDefault=False)
doneButton.setObjectName("Done")
doneButton.setCheckable(True)
doneButton.setStyleSheet("""* {background-color: #6f6; color: #000} *:hover { background-color: #7d7; color: #000 }""");
doneButton.clicked.connect(self.onDoneBtn)
delButton = QPushButton(self.tr("&Delete"), default=False, autoDefault=False)
delButton.setCheckable(True)
delButton.setStyleSheet("""* {background-color: #f66; color: #000} *:hover { background-color: #d77; color: #000 }""");
delButton.clicked.connect(self.onDelBtn)
BtnLayout1 = QHBoxLayout()
BtnLayout1.addWidget(delButton)
BtnLayout1.addWidget(doneButton)
verticalSpacer = QSpacerItem(800, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
BtnLayout1.addItem(verticalSpacer)
self.mainLayout.addLayout(BtnLayout1)
okButton = QPushButton(self.tr("&OK"), default=False, autoDefault=False)
okButton.setCheckable(True)
okButton.setStyleSheet("""* {background-color: #afa; color: #000} *:hover { background-color: #8d8; color: #000 }""");
okButton.clicked.connect(self.save)
cancelButton = QPushButton(self.tr("&Cancel"), default=False, autoDefault=False)
cancelButton.setCheckable(True)
cancelButton.setStyleSheet("""* {background-color: #faa; color: #000} *:hover { background-color: #d88; color: #000 }""");
cancelButton.clicked.connect(self.cancel)
BtnLayout2 = QHBoxLayout()
verticalSpacer = QSpacerItem(800, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
BtnLayout2.addItem(verticalSpacer)
BtnLayout2.addWidget(cancelButton)
BtnLayout2.addWidget(okButton)
self.mainLayout.addLayout(BtnLayout2)
def onAddProg(self):
if len(self.addProgEdit.text()):
newText = datetime.datetime.now().strftime("%y%m%d-%H%M%S ") + cleanString(self.addProgEdit.text())
self.progTextEdit.append(newText)
self.addProgEdit.setText('')
def save(self):
print('save')
self.onAddProg() #falls noch etwas in der Eingabezeile für Progess steht
self.item['Title'] = self.titleEdit.text()
cat = self.catSelCB.currentText()
if cat =='ALL':
cat = ''
self.item['Category'] = cat
self.item['Description'] = self.descriptionEdit.text()
self.item["Priority"] = self.prioEdit.text()
self.item["Status"] = self.statusEdit.text()
self.item["Date"] = qDateToDateStr(self.dateEdit.date())
self.item["DueDate"] = qDateToDateStr(self.dueDateEdit.date())
self.item["DoneDate"] = qDateToDateStr(self.doneDateEdit.date())
self.item["Progress"] = []
#text = self.progTextEdit.toPlainText().split('\n')
#print(text)
for line in self.progTextEdit.toPlainText().splitlines():
self.item["Progress"].append(line)
writeToDos()
reloadFile()
self.accept()
def cancel(self):
print('cancel')
self.reject()
def onDoneBtn(self):
print('done')
self.doneDateEdit.setDate(qDateFromStr(datetime.date.today().strftime("%Y-%m-%d")))
self.statusEdit.setText("DONE")
self.save()
def onDelBtn(self):
print('del')
self.doneDateEdit.setDate(qDateFromStr(datetime.date.today().strftime("%Y-%m-%d")))
self.statusEdit.setText("DELETED")
self.save()
# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
global darkScheme
shints = QGuiApplication.styleHints()
darkScheme = shints.colorScheme() == Qt.ColorScheme.Dark
self.setWindowTitle("ToDoPS6")
self.setMinimumSize(1600,700)
pixmapi = getattr(QStyle, 'SP_ArrowForward')
icon = self.style().standardIcon(pixmapi)
self.setWindowIcon(icon)
mainLayout = QVBoxLayout()
topLayout = QHBoxLayout()
mainWidget = QWidget()
mainWidget.setLayout(mainLayout)
self.setCentralWidget(mainWidget)
topWidget = QWidget()
topWidget.setLayout(topLayout)
mainLayout.addWidget(topWidget)
topWidget.setMaximumHeight(40);
ToDoButton = QPushButton("AddToDo")
ToDoButton.clicked.connect(self.onAddToDoButton)
topLayout.addWidget(ToDoButton)
self.statusFilterCB = QComboBox()
self.statusFilterCB.addItems(["Open", "Done", "All", "Deleted"])
self.statusFilterCB.setCurrentText("Open")
self.statusFilterCB.currentTextChanged.connect(self.onStatusFilterCB)
self.statusFilterCB.setMaximumWidth(90);
topLayout.addWidget(self.statusFilterCB)
self.categoriesCB = QComboBox()
self.categoriesCB.addItems(categories)
self.categoriesCB.currentTextChanged.connect(self.onCategoriesCB)
topLayout.addWidget(self.categoriesCB)
label = QLabel('Nothing will work unless you do.')
label.setMaximumHeight(30);
label.setAlignment(Qt.AlignCenter)
label.setStyleSheet("""
background-color: #99FF99;
color: #000;
font-family: Titillium;
font-size: 12px;
""")
topLayout.addWidget(label)
ReloadButton = QPushButton("Reload")
ReloadButton.clicked.connect(self.onReloadButton)
topLayout.addWidget(ReloadButton)
verticalSpacer = QSpacerItem(400, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
topLayout.addItem(verticalSpacer)
self.todoTable = QTableView()
mainLayout.addWidget(self.todoTable)
self.model = TableModel()
self.todoTable.setModel(self.model)
#Kontext Menü
self.todoTable.setContextMenuPolicy(Qt.CustomContextMenu)
self.todoTable.customContextMenuRequested.connect(self.showContextMenu)
self.todoTable.setShowGrid(False)
self.todoTable.verticalHeader().setStyleSheet("""font-weight: 800; font-size: 11px; """)
self.todoTable.horizontalHeader().setStyleSheet("""font-weight: 800;""")
self.todoTable.doubleClicked.connect(self.onSelTableItem)
self.todoTable.verticalHeader().setDefaultSectionSize(9); # Row height
#Category
self.todoTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(0, 120)
#Prio
self.todoTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(1, 60)
#Status
self.todoTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(2, 80)
#Title
#self.todoTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.todoTable.horizontalHeader().setSectionResizeMode(3, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(3, 300)
# Description
self.todoTable.horizontalHeader().setSectionResizeMode(4, QHeaderView.Stretch)
#Date
self.todoTable.horizontalHeader().setSectionResizeMode(5, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(5, 80)
#DueDate
self.todoTable.horizontalHeader().setSectionResizeMode(6, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(6, 80)
#DoneDate
self.todoTable.horizontalHeader().setSectionResizeMode(7, QHeaderView.Fixed)
self.todoTable.horizontalHeader().resizeSection(7, 70)
move_up_shortcut = QShortcut(QKeySequence(Qt.CTRL | Qt.Key_Up), self.todoTable)
move_up_shortcut.setContext(Qt.WidgetShortcut)
move_up_shortcut.activated.connect(self.moveUp)
move_down_shortcut = QShortcut(QKeySequence(Qt.CTRL | Qt.Key_Down), self.todoTable)
move_down_shortcut.setContext(Qt.WidgetShortcut)
move_down_shortcut.activated.connect(self.moveDown)
self.statusText = QLabel(toDoFile)
self.statusText.setMaximumHeight(20);
self.statusText.setStyleSheet("""
background-color: #ddd;
color: #000;
font-family: Titillium;
font-size: 11px;
""")
mainLayout.addWidget(self.statusText)
def saveItems(self):
print('Saving Items after reordering...')
writeToDos() # Die geänderte Reihenfolge speichern
def showContextMenu(self, position):
"""
Zeigt das Kontextmenü mit den Optionen "Move Up" und "Move Down".
"""
index = self.todoTable.indexAt(position)
if not index.isValid():
return
menu = QMenu(self)
move_up_action = QAction("Move Up", self)
move_up_action.triggered.connect(self.moveUp)
menu.addAction(move_up_action)
move_down_action = QAction("Move Down", self)
move_down_action.triggered.connect(self.moveDown)
menu.addAction(move_down_action)
menu.exec(self.todoTable.viewport().mapToGlobal(position))
def moveUp(self):
selected_row = self.todoTable.selectionModel().currentIndex().row()
if selected_row > 0: # Nur wenn das Item nicht schon die erste Zeile ist
item_id = self.model.filteredItems[selected_row]['ID']
moveItemInItemsObject(item_id, "up")
self.reloadTable() # Tabelle neu laden
self.todoTable.setCurrentIndex(self.model.index(selected_row - 1, 0))
def moveDown(self):
selected_row = self.todoTable.selectionModel().currentIndex().row()
if selected_row < len(self.model.filteredItems) - 1: # Nur wenn das Item nicht schon die letzte Zeile ist
item_id = self.model.filteredItems[selected_row]['ID']
moveItemInItemsObject(item_id, "down")
self.reloadTable() # Tabelle neu laden
self.todoTable.setCurrentIndex(self.model.index(selected_row + 1, 0))
def onAddToDoButton(self):
print ('click onAddToDoButton')
newObj = {
'ID': getNewID(),
'Category':'',
'Title':'',
'Description': '',
'Priority': '',
'Date': datetime.date.today().strftime("%Y-%m-%d"),
'DueDate': '',
'Status': "New",
'DoneDate': '',
'Progress': []
}
ItemsObject.append(newObj)
self.EditToDo(newObj)
def onStatusFilterCB(self, text):
global StatusFilter
StatusFilter = text
reloadFile()
print('Selected StatusFilter: '+str(text))
def onReloadButton(self):
reloadFile()
def onCategoriesCB(self, Text):
global CatSel
CatSel = Text
print("Selected Category: "+CatSel)
reloadFile()
def reloadTable(self):
print("window.reloadTable()")
self.model = TableModel()
self.todoTable.setModel(self.model)
def onSelTableItem(self, evt):
item = self.model.filteredItems[evt.row()]
self.EditToDo(item)
def EditToDo(self, item):
print(item)
dlg = EditDialog(item)
dlg.exec()
def getToDoItem(ID):
for item in ItemsObject:
if item['ID'] == ID:
print("getToDoItem("+str(ID)+")",item)
return item
return None
def getNewID():
maxId = 0
for i in ItemsObject:
if i['ID'] > maxId:
maxId = i['ID']
return maxId+1
def moveItemInItemsObject(item_id, direction):
global ItemsObject
# Holen der gefilterten Liste
filtered_items = getFilteredItems()
if not filtered_items:
return
from_index = None
for i, item in enumerate(filtered_items):
if item['ID'] == item_id:
from_index = i
break
if from_index is None:
return
if direction == "up":
neighbor_index = from_index - 1
elif direction == "down":
neighbor_index = from_index + 1
else:
return
if neighbor_index < 0 or neighbor_index >= len(filtered_items):
return
# Das Item das verschoben werden soll
item_to_move = filtered_items[from_index]
# Nachbar-Item bestimmen (höher/niedriger in filtered_items)
neighbor_item = filtered_items[neighbor_index]
# Finde die Position in ItemsObject
from_pos_global = ItemsObject.index(item_to_move)
# Finde die Position des Nachbar-Items in ItemsObject
neighbor_pos_global = ItemsObject.index(neighbor_item)
# Verschiebe das Item in ItemsObject zur richtigen Position
ItemsObject.pop(from_pos_global)
# Insert relativ zum Nachbar-Item (vorher/nachher), korrigiert um das Pop-Shift
if direction == "up":
insert_pos = neighbor_pos_global
if from_pos_global < neighbor_pos_global:
insert_pos -= 1
else:
insert_pos = neighbor_pos_global + 1
if from_pos_global < neighbor_pos_global:
insert_pos -= 1
ItemsObject.insert(insert_pos, item_to_move)
writeToDos()
reloadFile()
def writeToDos():
global toDoFile
global ItemsObject
print('writing ToDos to '+toDoFile)
toDoFO = io.open(toDoFile, mode="w", encoding="utf-8")
json.dump(ItemsObject, toDoFO, sort_keys=False, ensure_ascii=False, indent=2 )
toDoFO.close()
def loadToDoFile():
global ItemsObject
global toDoFile
global categories
global statusList
toDoFO = io.open(toDoFile, mode="r", encoding="utf-8")
ItemsObject = json.load(toDoFO)
toDoFO.close()
categories = ['ALL']
statusList = ['New', 'in Progress']
IDs = []
FixIdsNeeded = False
for item in ItemsObject:
if not item['Status'] in statusList:
if not item['Status'].lower() in ['done', 'deleted','',' ']:
statusList.append(item['Status'])
if not "DoneDate" in item:
item["DoneDate"] = ""
if not "Category" in item:
item["Category"] = ""
else:
if item["Category"] not in categories:
categories.append(item["Category"])
if item['ID'] not in IDs:
IDs.append(item['ID'])
else:
print("item "+item['Title'] +' has duplicate ID'+str(item['ID'])+', reset to -1 ! ')
FixIdsNeeded = True
item['ID'] = -1
if FixIdsNeeded:
#reassign IDs
for item in ItemsObject:
if item['ID'] == -1:
item['ID'] = getNewID()
writeToDos()
def reloadFile():
print("reloadFile()")
loadToDoFile()
window.reloadTable()
def createNewEmptyJson():
obj = [
{
'ID': 1,
'Title':'Test1',
'Description': 'Nur ein Test',
'Priority': 1,
'Date': '2024-07-01',
'DueDate': '',
'Status': "New",
'Category': 'Test',
'Progress': [],
'DoneDate': ''
}
]
fname = "ToDo.json"
newFile = io.open(fname, mode="w", encoding="utf-8")
json.dump(obj, newFile, sort_keys=False, ensure_ascii=False, indent=2 )
newFile.close()
return fname
if __name__ == '__main__':
global ItemsObject
global toDoFile
global window
global categories
global statusList
toDoFile = "ToDo.json"
if len(sys.argv) > 1:
print('using File: '+sys.argv[1])
toDoFile = sys.argv[1]
else:
if not exists(toDoFile):
toDoFile = createNewEmptyJson()
loadToDoFile()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()