-
Notifications
You must be signed in to change notification settings - Fork 1
/
groupable_tree_widget.py
1484 lines (1180 loc) · 57 KB
/
groupable_tree_widget.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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import time
import datetime
from PyQt5.QtWidgets import QWidget
import dateutil.parser as date_parser
from typing import Any, Dict, List, Union, Tuple, Type, Callable, Optional
from numbers import Number
from PyQt5 import QtWidgets, QtCore, QtGui
from theme.theme import set_theme
# Define example data
COLUMN_NAME_LIST = [
'shot_id',
'sequence',
'status',
'start_date',
'due_date',
'priority',
'shot_length',
'artist',
'department',
]
ID_TO_DATA_DICT = {
1: {
'shot_id': 'SHOT001',
'sequence': 'SEQ001',
'status': 'In Progress',
'start_date': '2023-06-17',
'due_date': '2023-07-15',
'priority': 2,
'shot_length': 150,
'artist': 'John Smith',
'department': 'Compositing'
},
2: {
'shot_id': 'SHOT002',
'sequence': 'SEQ001',
'status': 'Completed',
'start_date': '2023-06-20',
'due_date': '2023-07-10',
'priority': 1,
'shot_length': 200,
'artist': 'Jane Doe',
'department': 'Animation'
},
3: {
'shot_id': 'SHOT003',
'sequence': 'SEQ002',
'status': 'Not Started',
'start_date': '2023-06-25',
'due_date': '2023-07-20',
'priority': 3,
'shot_length': 120,
'artist': 'Alex Johnson',
'department': 'Lighting'
},
4: {
'shot_id': 'SHOT004',
'sequence': 'SEQ002',
'status': 'In Progress',
'start_date': '2023-06-18',
'due_date': '2023-07-25',
'priority': 2,
'shot_length': 180,
'artist': 'Emily Brown',
'department': 'Modeling'
},
5: {
'shot_id': 'SHOT005',
'sequence': 'SEQ003',
'status': 'Completed',
'start_date': '2023-06-22',
'due_date': '2023-07-12',
'priority': 1,
'shot_length': 250,
'artist': 'Michael Johnson',
'department': 'Rigging'
},
6: {
'shot_id': 'SHOT006',
'sequence': 'SEQ003',
'status': 'In Progress',
'start_date': '2023-06-30',
'due_date': '2023-07-30',
'priority': 3,
'shot_length': 130,
'artist': 'Sophia Wilson',
'department': 'Texturing'
},
7: {
'shot_id': 'SHOT007',
'sequence': 'SEQ004',
'status': 'Not Started',
'start_date': '2023-06-16',
'due_date': '2023-07-18',
'priority': 2,
'shot_length': 160,
'artist': 'Daniel Lee',
'department': 'Animation'
},
8: {
'shot_id': 'SHOT008',
'sequence': 'SEQ004',
'status': 'In Progress',
'start_date': '2023-06-25',
'due_date': '2023-07-25',
'priority': 2,
'shot_length': 190,
'artist': 'Olivia Davis',
'department': 'Compositing'
},
9: {
'shot_id': 'SHOT009',
'sequence': 'SEQ005',
'status': 'In Progress',
'start_date': '2023-06-19',
'due_date': '2023-07-20',
'priority': 3,
'shot_length': 140,
'artist': 'Noah Johnson',
'department': 'Lighting'
},
10: {
'shot_id': 'SHOT010',
'sequence': 'SEQ005',
'status': 'Completed',
'start_date': '2023-06-20',
'due_date': '2023-07-15',
'priority': 1,
'shot_length': 220,
'artist': 'Isabella Clark',
'department': 'Modeling'
},
}
def create_pastel_color(color: QtGui.QColor, saturation: float = 0.4, value: float = 0.9) -> QtGui.QColor:
"""Create a pastel version of the given color.
Args:
color (QtGui.QColor): The original color.
saturation (float): The desired saturation factor (default: 0.4).
value (float): The desired value/brightness factor (default: 0.9).
Returns:
QtGui.QColor: The pastel color.
"""
h, s, v, a = color.getHsvF()
# Decrease saturation and value to achieve a more pastel look
s *= saturation
v *= value
pastel_color = QtGui.QColor.fromHsvF(h, s, v, a)
return pastel_color
def parse_date(date_string: str) -> Optional[datetime.datetime]:
"""Parse the given date string into a datetime.datetime object.
Args:
date_string: The date string to parse.
Returns:
The parsed datetime object, or None if parsing fails.
"""
try:
parsed_date = date_parser.parse(date_string)
return parsed_date
except ValueError:
return None
class AdaptiveColorMappingDelegate(QtWidgets.QStyledItemDelegate):
"""A delegate class for adaptive color mapping in Qt items.
This delegate maps values to colors based on specified rules and color definitions.
It provides functionality to map numerical values, keywords, and date strings to colors.
Class Constants:
COLOR_DICT: A dictionary that maps color names to corresponding QColor objects.
Attributes:
min_value (Optional[Number]): The minimum value of the range.
max_value (Optional[Number]): The maximum value of the range.
min_color (QtGui.QColor): The color corresponding to the minimum value.
max_color (QtGui.QColor): The color corresponding to the maximum value.
keyword_color_dict (Dict[str, QtGui.QColor]): A dictionary that maps keywords to specific colors.
date_format (str): The date format string.
date_color_dict (Dict[str, QtGui.QColor]): A dictionary that caches colors for date values.
"""
# Class constants
# ---------------
COLOR_DICT = {
'pastel_green': create_pastel_color(QtGui.QColor(65, 144, 0)),
'pastel_red': create_pastel_color(QtGui.QColor(144, 0, 0)),
'red': QtGui.QColor(183, 26, 28),
'light_red': QtGui.QColor(183, 102, 77),
'light_green': QtGui.QColor(170, 140, 88),
'dark_green': QtGui.QColor(82, 134, 74),
'green': QtGui.QColor(44, 65, 44),
'blue': QtGui.QColor(0, 120, 215),
}
# Initialization and Setup
# ------------------------
def __init__(
self,
parent: Optional[QtCore.QObject] = None,
min_value: Optional[Number] = None,
max_value: Optional[Number] = None,
min_color: QtGui.QColor = COLOR_DICT['pastel_green'],
max_color: QtGui.QColor = COLOR_DICT['pastel_red'],
keyword_color_dict: Dict[str, QtGui.QColor] = dict(),
date_color_dict: Dict[str, QtGui.QColor] = dict(),
date_format: str = '%Y-%m-%d',
):
"""Initialize the AdaptiveColorMappingDelegate.
Args:
parent (QtCore.QObject, optional): The parent object. Default is None.
min_value (Number, optional): The minimum value of the range. Default is None.
max_value (Number, optional): The maximum value of the range. Default is None.
min_color (QtGui.QColor, optional): The color corresponding to the minimum value.
Default is a pastel green.
max_color (QtGui.QColor, optional): The color corresponding to the maximum value.
Default is a pastel red.
keyword_color_dict (Dict[str, QtGui.QColor], optional): A dictionary that maps
keywords to specific colors. Default is an empty dictionary.
date_format (str, optional): The date format string. Default is '%Y-%m-%d'.
"""
# Initialize the super class
super().__init__(parent)
# Store the arguments
self.min_value = min_value
self.max_value = max_value
self.min_color = min_color
self.max_color = max_color
self.keyword_color_dict = keyword_color_dict
self.date_color_dict = date_color_dict
self.date_format = date_format
# Private Methods
# ---------------
def _interpolate_color(self, value: Number) -> QtGui.QColor:
"""Interpolate between the min_color and max_color based on the given value.
Args:
value (Number): The value within the range.
Returns:
QtGui.QColor: The interpolated color.
"""
if not value:
return QtGui.QColor()
# Normalize the value between 0 and 1
normalized_value = (value - self.min_value) / (self.max_value - self.min_value)
# Interpolate between the min_color and max_color based on the normalized value
color = QtGui.QColor()
color.setRgbF(
self.min_color.redF() + (self.max_color.redF() - self.min_color.redF()) * normalized_value,
self.min_color.greenF() + (self.max_color.greenF() - self.min_color.greenF()) * normalized_value,
self.min_color.blueF() + (self.max_color.blueF() - self.min_color.blueF()) * normalized_value
)
return color
def _get_keyword_color(self, keyword: str, is_pastel_color: bool = True) -> QtGui.QColor:
"""Get the color associated with a keyword.
Args:
keyword (str): The keyword for which to retrieve the color.
Returns:
QtGui.QColor: The color associated with the keyword.
"""
if not keyword:
return QtGui.QColor()
# Check if the keyword color is already cached in the keyword_color_dict
if keyword in self.keyword_color_dict:
return self.keyword_color_dict[keyword]
# Generate a new color for the keyword
hue = (hash(keyword) % 360) / 360
saturation, value = 0.6, 0.6
keyword_color = QtGui.QColor.fromHsvF(hue, saturation, value)
# Optionally create a pastel version of the color
keyword_color = create_pastel_color(keyword_color, 0.6, 0.9) if is_pastel_color else keyword_color
# Cache the color in the keyword_color_dict
self.keyword_color_dict[keyword] = keyword_color
return keyword_color
def _get_deadline_color(self, difference: int) -> QtGui.QColor:
"""Get the color based on the difference from the current date.
Args:
difference (int): The difference in days from the current date.
Returns:
QtGui.QColor: The color corresponding to the difference.
"""
color_palette = {
0: self.COLOR_DICT['red'], # Red (today's deadline)
1: self.COLOR_DICT['light_red'], # Slightly lighter tone for tomorrow
2: self.COLOR_DICT['light_green'], # Light green for the day after tomorrow
**{diff: self.COLOR_DICT['dark_green']
for diff in range(3, 8)}, # Dark green for the next 3-7 days
}
if difference >= 7:
# Green for dates more than 7 days away
return self.COLOR_DICT['green']
else:
# Blue for other dates
return color_palette.get(difference, self.COLOR_DICT['blue'])
def _get_date_color(self, date_value: str, is_pastel_color: bool = True) -> QtGui.QColor:
"""Get the color based on the given date value.
Args:
date_value (str): The date string to determine the color for.
is_pastel_color (bool, optional): Whether to create a pastel version of the color.
Default is True.
Returns:
QtGui.QColor: The color corresponding to the date.
"""
# Check if the date color is already cached in the date_color_dict
if date_value in self.date_color_dict:
return self.date_color_dict[date_value]
# Get the current date
today = datetime.date.today()
# If a date format is specified, use datetime.strptime to parse the date string
if self.date_format:
# Use datetime.strptime to parse the date string
parsed_date = datetime.datetime.strptime(date_value, self.date_format).date()
else:
# Otherwise, use the parse_date function to parse the date string
parsed_date = parse_date(date_value).date()
# Calculate the difference in days between the parsed date and today
difference = (parsed_date - today).days
# Get the color based on the difference in days
date_color = self._get_deadline_color(difference)
# Optionally create a pastel version of the color
date_color = create_pastel_color(date_color, 0.6, 0.9) if is_pastel_color else date_color
# Cache the color in the date_color_dict
self.date_color_dict[date_value] = date_color
return date_color
# Event Handling or Override Methods
# ----------------------------------
def paint(self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, model_index: QtCore.QModelIndex):
"""Paint the delegate.
Args:
painter (QtGui.QPainter): The painter to use for drawing.
option (QtWidgets.QStyleOptionViewItem): The style option to use for drawing.
model_index (QtCore.QModelIndex): The model index of the item to be painted.
"""
# Retrieve the value from the model using UserRole
value = model_index.data(QtCore.Qt.ItemDataRole.UserRole)
if isinstance(value, Number):
# If the value is numerical, use _interpolate_color
color = self._interpolate_color(value)
elif isinstance(value, str):
if not parse_date(value):
# If the value is a string and not a date, use _get_keyword_color
color = self._get_keyword_color(value)
else:
# If the value is a date string, use _get_date_color
color = self._get_date_color(value)
else:
# For other data types, paint the item normally
super().paint(painter, option, model_index)
return
# If the current model index is in the target list, set the background color and style
option.backgroundBrush.setColor(color)
option.backgroundBrush.setStyle(QtCore.Qt.BrushStyle.SolidPattern)
# Fill the rect with the background brush
painter.fillRect(option.rect, option.backgroundBrush)
# Paint the item normally using the parent implementation
super().paint(painter, option, model_index)
class TreeWidgetItem(QtWidgets.QTreeWidgetItem):
"""A custom `QTreeWidgetItem` that can handle different data formats and store additional data in the user role.
Attributes:
id (int): The ID of the item.
"""
# Initialization and Setup
# ------------------------
def __init__(self, parent: Union[QtWidgets.QTreeWidget, QtWidgets.QTreeWidgetItem],
item_data: Union[Dict[str, Any], List[str]] = None,
item_id: int = None):
"""Initialize the `TreeWidgetItem` with the given parent and item data.
Args:
parent (Union[QtWidgets.QTreeWidget, QtWidgets.QTreeWidgetItem]): The parent `QTreeWidget` or QtWidgets.QTreeWidgetItem.
item_data (Union[Dict[str, Any], List[str]], optional): The data for the item. Can be a list of strings or a dictionary with keys matching the headers of the parent `QTreeWidget`. Defaults to `None`.
item_id (int, optional): The ID of the item. Defaults to `None`.
"""
# Set the item's ID
self.id = item_id
# If the data for the item is in list form
if isinstance(item_data, list):
item_data_list = item_data
# If the data for the item is in dictionary form
if isinstance(item_data, dict):
# Get the header item from the parent tree widget
header_item = parent.headerItem() if isinstance(parent, QtWidgets.QTreeWidget) else parent.treeWidget().headerItem()
# Get the column names from the header item
column_names = [header_item.text(i) for i in range(header_item.columnCount())]
# Create a list of data for the tree item
item_data_list = [item_id] + [item_data[column] if column in item_data.keys()
else str()
for column in column_names[1:]]
# Call the superclass's constructor to set the item's data
super().__init__(parent, map(str, item_data_list))
# Set the UserRole data for the item.
self._set_user_role_data(item_data_list)
# Private Methods
# ---------------
def _set_user_role_data(self, item_data_list: List[Any]):
"""Set the UserRole data for the item.
Args:
item_data_list (List[Any]): The list of data to set as the item's data.
"""
# Iterate through each column in the item
for column_index, value in enumerate(item_data_list):
# Set the value for the column in the UserRole data
self.set_value(column_index, value)
# Extended Methods
# ----------------
def get_child_level(self) -> int:
"""Get the child level of TreeWidgetItem
Returns:
int: The child level of the TreeWidgetItem
"""
# Set the current item as self
item = self
# Initialize child level
child_level = 0
# Iterate through the parent items to determine the child level
while item.parent():
# Increment child level for each parent
child_level += 1
# Update item to be its parent
item = item.parent()
# Return the final child level
return child_level
def get_model_indexes(self) -> List[QtCore.QModelIndex]:
"""Get the model index for each column in the tree widget.
Returns:
List[QtCore.QModelIndex]: A list of model index for each column in the tree widget.
"""
# Get a list of the shown column indices
shown_column_index_list = self.treeWidget().get_shown_column_index_list()
# Create a list to store the model index
model_indexes = list()
# Loop through each shown column index
for column_index in shown_column_index_list:
# Get the model index for the current column
model_index = self.treeWidget().indexFromItem(self, column_index)
# Add the model index to the list
model_indexes.append(model_index)
# Return the list of model index properties
return model_indexes
def get_value(self, column: Union[int, str]) -> Any:
"""Get the value of the item's UserRole data for the given column.
Args:
column (Union[int, str]): The column index or name.
Returns:
Any: The value of the UserRole data.
"""
# Get the column index from the column name if necessary
column_index = self.treeWidget().get_column_index(column) if isinstance(column, str) else column
# Get the UserRole data for the column
value = self.data(column_index, QtCore.Qt.ItemDataRole.UserRole)
# Fallback to the DisplayRole data if UserRole data is None
value = self.data(column_index, QtCore.Qt.ItemDataRole.DisplayRole) if value is None else value
return value
def set_value(self, column: Union[int, str], value: Any):
"""Set the value of the item's UserRole data for the given column.
Args:
column (Union[int, str]): The column index or name.
value (Any): The value to set.
"""
# Get the column index from the column name if necessary
column_index = self.treeWidget().get_column_index(column) if isinstance(column, str) else column
# Set the value for the column in the UserRole data
self.setData(column_index, QtCore.Qt.ItemDataRole.UserRole, value)
# Special Methods
# ---------------
def __getitem__(self, key: Union[int, str]) -> Any:
"""Get the value of the item's UserRole data for the given column.
Args:
key (Union[int, str]): The column index or name.
Returns:
Any: The value of the UserRole data.
"""
# Delegate the retrieval of the value to the `get_value` method
return self.get_value(key)
def __lt__(self, other_item: QtWidgets.QTreeWidgetItem) -> bool:
"""Sort the items in the tree widget based on their data.
Args:
other_item (QtWidgets.QTreeWidgetItem): The item to compare with.
Returns:
bool: Whether this item is less than the other item.
"""
# Get the column that is currently being sorted
column = self.treeWidget().sortColumn()
# Get the UserRole data for the column for both this item and the other item
self_data = self.get_value(column)
other_data = other_item.get_value(column)
# If the UserRole data is None, fallback to DisplayRole data
if other_data is None:
# Get the DisplayRole data for the column of the other item
other_data = other_item.data(column, QtCore.Qt.DisplayRole)
# If both UserRole data are None, compare their texts
if self_data is None and other_data is None:
return self.text(column) < other_item.text(column)
# If this item's UserRole data is None, it is considered greater
if self_data is None:
return True
# If the other item's UserRole data is None, this item is considered greater
if other_data is None:
return False
try:
# Try to compare the UserRole data directly
return self_data < other_data
except TypeError:
# If the comparison fails, compare their string representations
return str(self_data) < str(other_data)
class ColumnListWidget(QtWidgets.QListWidget):
def __init__(self, parent: QWidget) -> None:
super().__init__(parent)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.InternalMove)
self.tree_widget = parent
self.name_to_item = dict()
self.tree_widget.header().sectionMoved.connect(self.update_list)
self.model().rowsMoved.connect(self.update_tree_widget)
self.itemChanged.connect(self.set_column_visibility)
self.update_list()
def update_tree_widget(self):
item_texts = [self.item(i).text() for i in range(self.tree_widget.columnCount())]
for i, item_text in enumerate(item_texts):
column_index = self.tree_widget.get_column_index(item_text)
self.tree_widget.header().moveSection(self.tree_widget.header().visualIndex(column_index), i)
def set_column_visibility(self, item):
column_name = item.text()
is_hidden = item.checkState() == QtCore.Qt.CheckState.Unchecked
column_index = self.tree_widget.get_column_index(column_name)
self.tree_widget.setColumnHidden(column_index, is_hidden)
def update_list(self):
self.clear()
logical_indexes = [self.get_logical_index(i) for i in range(self.tree_widget.columnCount())]
header_names = [self.tree_widget.column_name_list[i] for i in logical_indexes]
self.addItems(header_names)
def get_logical_index(self, index):
return self.tree_widget.header().logicalIndex(index)
def addItems(self, items):
for column_index, item in enumerate(items):
if not isinstance(item, str):
continue
list_item = QtWidgets.QListWidgetItem(item)
list_item.setFlags(list_item.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
check_state = QtCore.Qt.CheckState.Unchecked if self.tree_widget.isColumnHidden(self.get_logical_index(column_index)) else QtCore.Qt.CheckState.Checked
list_item.setCheckState(check_state)
self.addItem(list_item)
self.name_to_item[item] = list_item
def get_item(self, item_name: str) -> QtWidgets.QListWidgetItem:
return self.name_to_item.get(item_name, None)
class GroupableTreeWidget(QtWidgets.QTreeWidget):
"""A QTreeWidget subclass that displays data in a tree structure with the ability to group data by a specific column.
Attributes:
column_name_list (List[str]): The list of column names to be displayed in the tree widget.
id_to_data_dict (Dict[int, Dict[str, str]]): A dictionary mapping item IDs to their data as a dictionary.
groups (Dict[str, TreeWidgetItem]): A dictionary mapping group names to their tree widget items.
_is_middle_button_pressed (bool): Indicates if the middle mouse button is pressed.
It's used for scrolling functionality when the middle button is pressed and the mouse is moved.
_middle_button_prev_pos (QtCore.QPoint): The previous position of the mouse when the middle button was pressed.
_middle_button_start_pos (QtCore.QPoint): The initial position of the mouse when the middle button was pressed.
_mouse_move_timestamp (float): The timestamp of the last mouse movement.
"""
# Signals emitted by the GroupableTreeWidget
ungrouped_all = QtCore.pyqtSignal()
grouped_by_column = QtCore.pyqtSignal(str)
# Initialization and Setup
# ------------------------
def __init__(self, parent: QtWidgets.QWidget = None,
column_name_list: List[str] = list(),
id_to_data_dict: Dict[int, Dict[str, str]] = dict()):
# Call the parent class constructor
super().__init__(parent)
# Store the column names and data dictionary for later use
self.column_name_list = column_name_list
self.id_to_data_dict = id_to_data_dict
# Set up the initial values
self._setup_attributes()
# Set up the UI
self._setup_ui()
# Set up signal connections
self._setup_signal_connections()
def _setup_attributes(self):
"""Set up the initial values for the widget.
"""
# Attributes
# ----------
# Store the current grouped column name
self.grouped_column_name = str()
#
self.id_to_tree_item = dict()
# Private Attributes
# ------------------
# Initialize middle button pressed flag
self._is_middle_button_pressed = False
# Previous position of the middle mouse button
self._middle_button_prev_pos = QtCore.QPoint()
# Initial position of the middle mouse button
self._middle_button_start_pos = QtCore.QPoint()
# Timestamp of the last mouse move event
self._mouse_move_timestamp = float()
self._row_height = 24
def _setup_ui(self):
"""Set up the UI for the widget, including creating widgets and layouts.
"""
# Initializes scroll modes for the widget.
self.setVerticalScrollMode(QtWidgets.QTreeWidget.ScrollMode.ScrollPerPixel)
self.setHorizontalScrollMode(QtWidgets.QTreeWidget.ScrollMode.ScrollPerPixel)
# Set up the context menu for the header
self.header().setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
# Set up the columns
self.set_column_name_list(self.column_name_list)
# Add the data to the widget
self.add_items(self.id_to_data_dict)
# Enable sorting in the tree widget
self.setSortingEnabled(True)
self.setWordWrap(True)
# Enable ExtendedSelection mode for multi-select and set the selection behavior to SelectItems
self.setSelectionMode(QtWidgets.QTreeWidget.SelectionMode.ExtendedSelection)
self.setSelectionBehavior(QtWidgets.QTreeWidget.SelectionBehavior.SelectItems)
self.set_row_height(self._row_height)
def _setup_signal_connections(self):
"""Set up signal connections between widgets and slots.
"""
# Connect signal of header
self.header().customContextMenuRequested.connect(self._on_header_context_menu)
self.itemExpanded.connect(self.toggle_expansion_for_selected)
self.itemCollapsed.connect(self.toggle_expansion_for_selected)
self.header().sortIndicatorChanged.connect(lambda _: self.set_row_height(self._row_height))
# Key Binds
# ---------
# Create a shortcut for the copy action and connect its activated signal
copy_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence.StandardKey.Copy, self)
copy_shortcut.activated.connect(self.copy_selected_cells)
# Private Methods
# ---------------
def _on_header_context_menu(self, pos: QtCore.QPoint) -> None:
"""Show a context menu for the header of the tree widget.
Context Menu:
+-------------------------------+
| Grouping |
| - Group by this column |
| - Ungroup all |
| ----------------------------- |
| Visualization |
| - Set Color Adaptive |
| - Reset All Color Adaptive |
| ----------------------------- |
| - Fit in View |
| ----------------------------- |
| Manage Columns |
| - Show/Hide Columns > |
| - Hide This Column |
+-------------------------------+
Args:
pos (QtCore.QPoint): The position where the right click occurred.
"""
# Get the index of the column where the right click occurred
column = self.header().logicalIndexAt(pos)
# Create the context menu
# NOTE: Check if the widget has a 'scalable_view' attribute and if it is an instance of QtWidgets.QGraphicsView
# If 'scalable_view' is available and is an instance of QtWidgets.QGraphicsView, use it as the parent for the menu
# This ensures that the context menu is displayed correctly within the view
# Otherwise, use self as the parent for the menu
if hasattr(self, 'scalable_view') and isinstance(self.scalable_view, QtWidgets.QGraphicsView):
menu = QtWidgets.QMenu(self.scalable_view)
else:
menu = QtWidgets.QMenu(self)
self.add_label_action(menu, 'Grouping')
# Create the 'Group by this column' action and connect it to the 'group_by_column' method. Pass in the selected column as an argument.
group_by_action = menu.addAction('Group by this column')
group_by_action.triggered.connect(lambda: self.group_by_column(column))
# Create the 'Ungroup all' action and connect it to the 'ungroup_all' method
ungroup_all_action = menu.addAction('Ungroup all')
ungroup_all_action.triggered.connect(self.ungroup_all)
# Add a separator
menu.addSeparator()
self.add_label_action(menu, 'Visualization')
# Create the 'Set Color Adaptive' action and connect it to the 'apply_column_color_adaptive' method
apply_color_adaptive_action = menu.addAction('Set Color Adaptive')
apply_color_adaptive_action.triggered.connect(lambda: self.apply_column_color_adaptive(column))
# Create the 'Reset All Color Adaptive' action and connect it to the 'reset_all_color_adaptive_column' method
reset_all_color_adaptive_action = menu.addAction('Reset All Color Adaptive')
reset_all_color_adaptive_action.triggered.connect(self.reset_all_color_adaptive_column)
# Add a separator
menu.addSeparator()
# Add the 'Fit in View' action and connect it to the 'fit_column_in_view' method
fit_column_in_view_action = menu.addAction('Fit in View')
fit_column_in_view_action.triggered.connect(self.fit_column_in_view)
# Add a separator
menu.addSeparator()
self.add_label_action(menu, 'Manage Columns')
show_hide_column = menu.addMenu('Show/Hide Columns')
menu.addMenu(show_hide_column)
self.column_list_widget = ColumnListWidget(self)
action = QtWidgets.QWidgetAction(self)
action.setDefaultWidget(self.column_list_widget)
show_hide_column.addAction(action)
hide_this_column = menu.addAction('Hide This Column')
hide_this_column.triggered.connect(lambda: self.hideColumn(column))
# Disable 'Group by this column' on the first column
if not column:
group_by_action.setDisabled(True)
# Show the context menu
menu.popup(QtGui.QCursor.pos())
def add_label_action(self, parent_menu: QtWidgets.QMenu, text: str):
label = QtWidgets.QLabel(text, parent_menu)
label.setDisabled(True)
label.setStyleSheet(
'color: rgb(144, 144, 144); padding: 0px;'
)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(label)
widget = QtWidgets.QWidget()
widget.setLayout(layout)
action = QtWidgets.QWidgetAction(parent_menu)
action.setDefaultWidget(widget)
parent_menu.addAction(action)
def _create_item_groups(self, data: List[str]) -> Dict[str, List[TreeWidgetItem]]:
"""Group the data into a dictionary mapping group names to lists of tree items.
Args:
data (List[str]): The data to be grouped.
Returns:
Dict[str, List[TreeWidgetItem]]: A dictionary mapping group names to lists of tree items.
"""
# Create a dictionary to store the groups
groups = {}
# Group the data
for i, item_data in enumerate(data):
# If the data is empty, add it to the '_others' group
if not item_data:
item_data = '_others'
# Add the tree item to the appropriate group
item = self.topLevelItem(i)
if item_data in groups:
groups[item_data].append(item)
else:
groups[item_data] = [item]
return groups
def _apply_scroll_momentum(self, velocity: QtCore.QPointF, momentum_factor: float = 0.5) -> None:
"""Applies momentum to the scroll bars based on the given velocity.
Args:
velocity (QtCore.QPointF): The velocity of the mouse movement.
momentum_factor (float, optional): The factor to control the momentum strength. Defaults to 0.5.
"""
# Calculate horizontal and vertical momentum based on velocity and momentum factor
horizontal_momentum = int(velocity.x() * momentum_factor)
vertical_momentum = int(velocity.y() * momentum_factor)
# Scroll horizontally and vertically with animation using the calculated momenta
self._animate_scroll(self.horizontalScrollBar(), horizontal_momentum)
self._animate_scroll(self.verticalScrollBar(), vertical_momentum)
def _animate_scroll(self, scroll_bar: QtWidgets.QScrollBar, momentum: int) -> None:
"""Animates the scrolling of the given scroll bar to the target value over the specified duration.
Args:
scroll_bar (QtWidgets.QScrollBar): The scroll bar to animate.
momentum (int): The momentum value to scroll.
"""
# Get the current value of the scroll bar
current_value = scroll_bar.value()
# Calculate the target value by subtracting the momentum from the current value
target_value = current_value - momentum
# Calculate the duration of the animation based on the absolute value of the momentum
duration = min(abs(momentum) * 20, 500)
# Get the start time of the animation
start_time = time.time()
def _perform_scroll_animation():
"""Animates the scrolling of the given scroll bar to the target value over the specified duration.
The animation interpolates the scroll bar value from the current value to the target value based on the elapsed time.
"""
# Access the current_value variable from the enclosing scope
nonlocal current_value
# Stop the animation if the middle mouse button is pressed
if self._is_middle_button_pressed:
return
# Calculate the elapsed time since the start of the animation
elapsed_time = int((time.time() - start_time) * 1000)
# Check if the elapsed time has reached the duration
if elapsed_time >= duration:
# Animation complete
scroll_bar.setValue(target_value)
return
# Calculate the interpolated value based on elapsed time and duration
progress = elapsed_time / duration
interpolated_value = int(current_value + (target_value - current_value) * progress)
# Update the scroll bar value and schedule the next animation frame
scroll_bar.setValue(interpolated_value)
QtCore.QTimer.singleShot(10, _perform_scroll_animation)
# Start the animation
_perform_scroll_animation()
# Extended Methods
# ----------------
# NOTE: for refactoring
def set_row_height(self, height):
if not self.topLevelItem(0):
return
self.setUniformRowHeights(True)
for column_index in range(self.columnCount()):
size_hint = self.sizeHintForColumn(column_index)
self.topLevelItem(0).setSizeHint(column_index, QtCore.QSize(size_hint, height))
def reset_row_height(self):
if not self.topLevelItem(0):
return
self.setUniformRowHeights(False)
for column_index in range(self.columnCount()):
size_hint = self.sizeHintForColumn(column_index)
self.topLevelItem(0).setSizeHint(column_index, QtCore.QSize(size_hint, -1))
def toggle_expansion_for_selected(self, item):
"""Toggles the expansion state of selected items.
Args:
item: The clicked item whose expansion state will be used as a reference.
Returns:
None.
"""
# Get the currently selected items
selected_items = self.selectedItems()
# If no items are selected, return early
if not selected_items:
return
# Set the expanded state of all selected items to match the expanded state of the clicked item
for i in selected_items:
i.setExpanded(item.isExpanded())
def get_column_value_range(self, column: int, child_level: int = 0) -> Tuple[Optional[Number], Optional[Number]]:
"""Get the value range of a specific column at a given child level.