Repository navigation
Expand file tree
/
Copy pathcode_source.py
More file actions
2655 lines (2183 loc) · 89.2 KB
/
Copy pathcode_source.py
File metadata and controls
2655 lines (2183 loc) · 89.2 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
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
# FILE: src\fluent_multiselect\chips.py
# FILE: src/fluent_multiselect/chips.py
"""Fluent Design chip widgets for multi-select display."""
from typing import List, Tuple, Optional
from PyQt6.QtWidgets import QWidget
from PyQt6.QtGui import (
QPainter,
QColor,
QPen,
QPainterPath,
QFontMetrics,
QPaintEvent,
QMouseEvent,
QFont,
)
from PyQt6.QtCore import Qt, pyqtSignal, QRectF, QPointF, QEvent
from .styles import Theme
class FluentChipsDisplay(QWidget):
"""
Widget that displays selected items as chips with remove buttons.
Each chip shows the item text and an X button to remove it.
Chips that don't fit are shown as "+N" overflow indicator.
Signals:
chipRemoved: Emitted when a chip's X button is clicked, with row index.
clicked: Emitted when clicking on empty area (to open popup).
Example:
display = FluentChipsDisplay(theme=Theme.DARK)
display.setItems([(0, "Python"), (2, "JavaScript")])
display.chipRemoved.connect(lambda idx: print(f"Remove item at row {idx}"))
"""
chipRemoved = pyqtSignal(int) # Emits row index of removed item
clicked = pyqtSignal() # Emitted when clicking on empty area
# Visual constants
CHIP_HEIGHT = 22
CHIP_BORDER_RADIUS = 11
CHIP_PADDING_LEFT = 10
CHIP_PADDING_RIGHT = 6
CHIP_SPACING = 4
X_BUTTON_SIZE = 16
X_ICON_SIZE = 3.5
X_STROKE_WIDTH = 1.6
def __init__(self, parent: Optional[QWidget] = None, theme: Theme = Theme.DARK):
"""
Initialize the chips display widget.
Args:
parent: Parent widget.
theme: Visual theme (Theme.DARK or Theme.LIGHT).
"""
super().__init__(parent)
self._theme = theme
self._items: List[Tuple[int, str]] = [] # List of (row_idx, text)
self._chip_rects: List[Tuple[int, QRectF, QRectF]] = [] # (row_idx, chip_rect, x_rect)
self._hovered_chip: int = -1
self._hovered_x: int = -1
self._placeholder_text: str = ""
self._max_visible_chips: Optional[int] = None
self.setMouseTracking(True)
self.setCursor(Qt.CursorShape.ArrowCursor)
self.setMinimumHeight(28)
# Set font
font = QFont("Segoe UI", 9)
self.setFont(font)
def setItems(self, items: List[Tuple[int, str]]) -> None:
"""
Set the items to display as chips.
Args:
items: List of (row_index, display_text) tuples.
"""
self._items = list(items)
self._chip_rects.clear()
self._hovered_chip = -1
self._hovered_x = -1
self.update()
def items(self) -> List[Tuple[int, str]]:
"""Get the current items."""
return list(self._items)
def setPlaceholderText(self, text: str) -> None:
"""
Set placeholder text shown when no items are selected.
Args:
text: Placeholder text.
"""
self._placeholder_text = text
self.update()
def placeholderText(self) -> str:
"""Get the placeholder text."""
return self._placeholder_text
def setMaxVisibleChips(self, count: Optional[int]) -> None:
"""
Set maximum number of visible chips before showing overflow.
Args:
count: Maximum chips to show, or None for auto (based on width).
"""
self._max_visible_chips = count
self.update()
def maxVisibleChips(self) -> Optional[int]:
"""Get the maximum visible chips setting."""
return self._max_visible_chips
def setTheme(self, theme: Theme) -> None:
"""
Set the display theme.
Args:
theme: Theme.DARK or Theme.LIGHT.
"""
self._theme = theme
self.update()
def theme(self) -> Theme:
"""Get the current theme."""
return self._theme
def clear(self) -> None:
"""Clear all chips."""
self._items.clear()
self._chip_rects.clear()
self._hovered_chip = -1
self._hovered_x = -1
self.update()
def paintEvent(self, event: QPaintEvent) -> None:
"""Paint the chips."""
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setFont(self.font())
self._chip_rects.clear()
if not self._items:
self._draw_placeholder(painter)
return
self._draw_chips(painter)
def _draw_placeholder(self, painter: QPainter) -> None:
"""Draw placeholder text when no items are selected."""
if not self._placeholder_text:
return
color = self._get_placeholder_color()
painter.setPen(color)
text_rect = self.rect().adjusted(8, 0, -35, 0)
painter.drawText(
text_rect,
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
self._placeholder_text,
)
def _draw_chips(self, painter: QPainter) -> None:
"""Draw all chips with overflow handling."""
x = self.CHIP_SPACING
y = (self.height() - self.CHIP_HEIGHT) // 2
max_width = self.width() - 40 # Leave space for dropdown arrow
fm = QFontMetrics(self.font())
visible_count = 0
for row_idx, text in self._items:
# Check max visible limit
if self._max_visible_chips is not None:
if visible_count >= self._max_visible_chips:
break
# Calculate chip width
text_width = fm.horizontalAdvance(text)
chip_width = (
self.CHIP_PADDING_LEFT
+ text_width
+ self.CHIP_PADDING_RIGHT
+ self.X_BUTTON_SIZE
+ 2
)
# Check if chip fits
if x + chip_width > max_width and visible_count > 0:
break
# Create rectangles
chip_rect = QRectF(x, y, chip_width, self.CHIP_HEIGHT)
x_rect = QRectF(
x + chip_width - self.X_BUTTON_SIZE - 4,
y + (self.CHIP_HEIGHT - self.X_BUTTON_SIZE) / 2,
self.X_BUTTON_SIZE,
self.X_BUTTON_SIZE,
)
# Draw the chip
self._draw_chip(painter, chip_rect, x_rect, text, row_idx)
self._chip_rects.append((row_idx, chip_rect, x_rect))
x += chip_width + self.CHIP_SPACING
visible_count += 1
# Draw overflow indicator
remaining = len(self._items) - visible_count
if remaining > 0:
self._draw_overflow(painter, x, y, remaining)
def _draw_chip(
self, painter: QPainter, chip_rect: QRectF, x_rect: QRectF, text: str, row_idx: int
) -> None:
"""Draw a single chip with text and X button."""
is_hovered = self._hovered_chip == row_idx
is_x_hovered = self._hovered_x == row_idx
colors = self._get_chip_colors(is_hovered, is_x_hovered)
# Draw chip background
path = QPainterPath()
path.addRoundedRect(chip_rect, self.CHIP_BORDER_RADIUS, self.CHIP_BORDER_RADIUS)
painter.fillPath(path, colors["background"])
painter.setPen(QPen(colors["border"], 1))
painter.drawPath(path)
# Draw text
text_rect = chip_rect.adjusted(
self.CHIP_PADDING_LEFT, 0, -(self.X_BUTTON_SIZE + self.CHIP_PADDING_RIGHT), 0
)
painter.setPen(colors["text"])
painter.drawText(
text_rect.toRect(), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, text
)
# Draw X button hover background
if is_x_hovered:
x_bg_path = QPainterPath()
x_bg_path.addEllipse(x_rect)
painter.fillPath(x_bg_path, colors["x_hover_bg"])
# Draw X icon
self._draw_x_icon(painter, x_rect, colors["x"])
def _draw_x_icon(self, painter: QPainter, rect: QRectF, color: QColor) -> None:
"""Draw the X (close) icon."""
painter.setPen(
QPen(color, self.X_STROKE_WIDTH, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)
)
cx, cy = rect.center().x(), rect.center().y()
size = self.X_ICON_SIZE
painter.drawLine(QPointF(cx - size, cy - size), QPointF(cx + size, cy + size))
painter.drawLine(QPointF(cx - size, cy + size), QPointF(cx + size, cy - size))
def _draw_overflow(self, painter: QPainter, x: float, y: float, count: int) -> None:
"""Draw the overflow indicator (+N)."""
colors = self._get_chip_colors(False, False)
overflow_text = f"+{count}"
fm = QFontMetrics(self.font())
text_width = fm.horizontalAdvance(overflow_text)
# Draw overflow chip (without X button)
chip_rect = QRectF(x, y, text_width + 16, self.CHIP_HEIGHT)
path = QPainterPath()
path.addRoundedRect(chip_rect, self.CHIP_BORDER_RADIUS, self.CHIP_BORDER_RADIUS)
painter.fillPath(path, colors["overflow_bg"])
painter.setPen(QPen(colors["border"], 1))
painter.drawPath(path)
# Draw text
painter.setPen(colors["text"])
painter.drawText(chip_rect.toRect(), Qt.AlignmentFlag.AlignCenter, overflow_text)
def _get_chip_colors(self, is_hovered: bool, is_x_hovered: bool) -> dict:
"""Get colors for chip rendering based on theme and state."""
if self._theme == Theme.DARK:
return {
"background": QColor(255, 255, 255, 35 if is_hovered else 25),
"border": QColor(255, 255, 255, 50 if is_hovered else 35),
"text": QColor(255, 255, 255),
"x": QColor(255, 255, 255, 230 if is_x_hovered else 160),
"x_hover_bg": QColor(255, 255, 255, 50),
"overflow_bg": QColor(255, 255, 255, 15),
}
else:
return {
"background": QColor(0, 0, 0, 18 if is_hovered else 10),
"border": QColor(0, 0, 0, 30 if is_hovered else 18),
"text": QColor(0, 0, 0),
"x": QColor(0, 0, 0, 210 if is_x_hovered else 130),
"x_hover_bg": QColor(0, 0, 0, 35),
"overflow_bg": QColor(0, 0, 0, 8),
}
def _get_placeholder_color(self) -> QColor:
"""Get the placeholder text color based on theme."""
if self._theme == Theme.DARK:
return QColor(255, 255, 255, 120)
return QColor(0, 0, 0, 100)
def mouseMoveEvent(self, event: QMouseEvent) -> None:
"""Handle mouse movement for hover effects."""
pos = event.position()
old_chip = self._hovered_chip
old_x = self._hovered_x
self._hovered_chip = -1
self._hovered_x = -1
for row_idx, chip_rect, x_rect in self._chip_rects:
if x_rect.contains(pos):
self._hovered_x = row_idx
self._hovered_chip = row_idx
self.setCursor(Qt.CursorShape.PointingHandCursor)
break
elif chip_rect.contains(pos):
self._hovered_chip = row_idx
self.setCursor(Qt.CursorShape.ArrowCursor)
break
else:
self.setCursor(Qt.CursorShape.ArrowCursor)
if old_chip != self._hovered_chip or old_x != self._hovered_x:
self.update()
super().mouseMoveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None:
"""Handle mouse press to remove chips or open popup."""
if event.button() != Qt.MouseButton.LeftButton:
super().mousePressEvent(event)
return
pos = event.position()
# Check if clicked on X button
for row_idx, chip_rect, x_rect in self._chip_rects:
if x_rect.contains(pos):
self.chipRemoved.emit(row_idx)
event.accept()
return
# Click was not on an X button, emit clicked to open popup
self.clicked.emit()
event.accept()
def leaveEvent(self, event: QEvent) -> None:
"""Handle mouse leave."""
self._hovered_chip = -1
self._hovered_x = -1
self.update()
super().leaveEvent(event)
def resizeEvent(self, event) -> None:
"""Handle resize to update chip layout."""
super().resizeEvent(event)
self.update()
# FILE: src\fluent_multiselect\colors.py
# FILE: src/fluent_multiselect/colors.py
"""Fluent Design color definitions."""
from PyQt6.QtGui import QColor
class FluentColors:
"""Fluent Design color palette for light and dark themes."""
# Dark theme colors
DARK_BACKGROUND = QColor(32, 32, 32)
DARK_SURFACE = QColor(44, 44, 44)
DARK_BORDER = QColor(255, 255, 255, 14)
DARK_BORDER_HOVER = QColor(255, 255, 255, 21)
DARK_TEXT = QColor(255, 255, 255)
DARK_TEXT_SECONDARY = QColor(255, 255, 255, 163)
DARK_TEXT_DISABLED = QColor(255, 255, 255, 92) # QSS: rgba(255, 255, 255, 0.36)
DARK_ACCENT = QColor(138, 180, 248)
DARK_ACCENT_HOVER = QColor(158, 195, 255)
DARK_ACCENT_PRESSED = QColor(118, 165, 235)
DARK_CHECKBOX_BG = QColor(255, 255, 255, 14)
DARK_CHECKBOX_BORDER = QColor(255, 255, 255, 70) # QSS: rgba(255, 255, 255, 0.27)
DARK_CHECKBOX_CHECKED = QColor(138, 180, 248)
DARK_CHECK_MARK = QColor(0, 0, 0)
# Light theme colors
LIGHT_BACKGROUND = QColor(255, 255, 255)
LIGHT_SURFACE = QColor(252, 252, 252)
LIGHT_BORDER = QColor(0, 0, 0, 19)
LIGHT_BORDER_HOVER = QColor(0, 0, 0, 27)
LIGHT_TEXT = QColor(0, 0, 0)
LIGHT_TEXT_SECONDARY = QColor(0, 0, 0, 163)
LIGHT_TEXT_DISABLED = QColor(0, 0, 0, 92) # QSS: rgba(0, 0, 0, 0.36)
LIGHT_ACCENT = QColor(0, 103, 192)
LIGHT_ACCENT_HOVER = QColor(0, 123, 212)
LIGHT_ACCENT_PRESSED = QColor(0, 83, 172)
LIGHT_CHECKBOX_BG = QColor(0, 0, 0, 14)
LIGHT_CHECKBOX_BORDER = QColor(0, 0, 0, 90) # QSS: rgba(0, 0, 0, 0.35)
LIGHT_CHECKBOX_CHECKED = QColor(0, 103, 192)
LIGHT_CHECK_MARK = QColor(255, 255, 255)
@classmethod
def get_accent_color(cls, dark: bool = True) -> QColor:
"""Get the accent color for the specified theme."""
return cls.DARK_ACCENT if dark else cls.LIGHT_ACCENT
@classmethod
def get_text_color(cls, dark: bool = True) -> QColor:
"""Get the primary text color for the specified theme."""
return cls.DARK_TEXT if dark else cls.LIGHT_TEXT
@classmethod
def get_disabled_text_color(cls, dark: bool = True) -> QColor:
"""Get the disabled text color for the specified theme (QSS: 0.36 alpha)."""
return cls.DARK_TEXT_DISABLED if dark else cls.LIGHT_TEXT_DISABLED
@classmethod
def get_checkbox_colors(cls, dark: bool = True) -> dict:
"""Get all checkbox-related colors for the specified theme."""
if dark:
return {
'background': cls.DARK_CHECKBOX_BG,
'border': cls.DARK_CHECKBOX_BORDER,
'checked': cls.DARK_CHECKBOX_CHECKED,
'check_mark': cls.DARK_CHECK_MARK,
'accent_hover': cls.DARK_ACCENT_HOVER,
'accent_pressed': cls.DARK_ACCENT_PRESSED,
}
else:
return {
'background': cls.LIGHT_CHECKBOX_BG,
'border': cls.LIGHT_CHECKBOX_BORDER,
'checked': cls.LIGHT_CHECKBOX_CHECKED,
'check_mark': cls.LIGHT_CHECK_MARK,
'accent_hover': cls.LIGHT_ACCENT_HOVER,
'accent_pressed': cls.LIGHT_ACCENT_PRESSED,
}
# FILE: src\fluent_multiselect\combobox.py
# FILE: src/fluent_multiselect/combobox.py
"""
Fluent Design MultiSelect ComboBox for PyQt6.
A multi-select combo box widget styled according to Windows 11 Fluent Design.
"""
from typing import Any, List, Optional, Set, Union
from PyQt6.QtWidgets import (
QComboBox,
QLineEdit,
QWidget,
QGraphicsDropShadowEffect,
QHBoxLayout,
QStackedWidget,
)
from PyQt6.QtGui import (
QStandardItem,
QStandardItemModel,
QFontMetrics,
QCursor,
QPainter,
QColor,
QPen,
QPainterPath,
QMouseEvent,
QPaintEvent,
QEnterEvent,
QWheelEvent,
QKeyEvent,
)
from PyQt6.QtCore import (
Qt,
QEvent,
pyqtSignal,
QObject,
QRect,
QPropertyAnimation,
QEasingCurve,
pyqtProperty,
QRectF,
QModelIndex,
QAbstractItemModel,
)
from .styles import Theme, FluentStyleSheet
from .colors import FluentColors
from .delegate import FluentCheckBoxDelegate
from .chips import FluentChipsDisplay
class FluentLineEdit(QLineEdit):
"""Custom read-only line edit for the combo box display."""
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
self.setReadOnly(True)
self.setCursor(Qt.CursorShape.ArrowCursor)
def mousePressEvent(self, event: QMouseEvent) -> None:
"""Prevent text selection on click."""
event.accept()
def mouseDoubleClickEvent(self, event: QMouseEvent) -> None:
"""Prevent text selection on double click."""
event.accept()
class FluentMultiSelectComboBox(QComboBox):
"""
A Fluent Design styled multi-select combo box for PyQt6.
This widget allows selecting multiple items from a dropdown list with
Windows 11 Fluent Design styling.
Signals:
selectionChanged: Emitted when selection changes, with list of selected values.
Example:
combo = FluentMultiSelectComboBox(theme=Theme.DARK)
combo.addItems(["Python", "JavaScript", "TypeScript"])
combo.setSelectAllEnabled(True)
combo.setChipsEnabled(True) # Enable chips display with X buttons
combo.selectionChanged.connect(lambda items: print(f"Selected: {items}"))
"""
selectionChanged = pyqtSignal(list)
# Constants
_SELECT_ALL_DATA = "__select_all__"
def __init__(self, parent: Optional[QWidget] = None, theme: Theme = Theme.DARK):
"""
Initialize the FluentMultiSelectComboBox.
Args:
parent: Parent widget.
theme: Theme to use (Theme.DARK or Theme.LIGHT).
"""
super().__init__(parent)
# Configuration
self._theme = theme
self._placeholder_text = ""
self._display_delimiter = ", "
self._output_type = "data"
self._display_type = "text"
self._duplicates_enabled = True
self._max_selection_count: Optional[int] = None
self._close_on_select = False
self._select_all_enabled = False
self._select_all_text = "Select All"
# Visual configuration
self._focus_border_enabled = False
self._focus_border_width = 2
self._focus_border_position = "bottom"
# Chips configuration
self._chips_enabled = False
self._chips_display: Optional[FluentChipsDisplay] = None
# State
self._checked_rows: Set[int] = set()
self._last_selection_snapshot: List[Any] = []
self._in_bulk_update = False
self._updating_text = False
self._hovered = False
self._pressed = False
self._popup_visible = False
self._arrow_rotation = 0.0
self._setup_ui()
self._apply_theme()
self._connect_model_signals(self.model())
self._rebuild_checked_cache()
self.updateText()
def _setup_ui(self) -> None:
"""Setup the UI components."""
self.setEditable(True)
line_edit = FluentLineEdit(self)
self.setLineEdit(line_edit)
line_edit.installEventFilter(self)
self._delegate = FluentCheckBoxDelegate(self, self._theme)
self.setItemDelegate(self._delegate)
view = self.view()
view.setMouseTracking(True)
view.viewport().installEventFilter(self)
view.installEventFilter(self)
if hasattr(view, "setUniformItemSizes"):
view.setUniformItemSizes(True)
# Setup arrow animation
self._arrow_animation = QPropertyAnimation(self, b"arrowRotation")
self._arrow_animation.setDuration(150)
self._arrow_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
self.setMinimumHeight(32)
self.setMinimumWidth(120)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
def _setup_chips_display(self) -> None:
"""Setup the chips display widget."""
if self._chips_display is not None:
return
self._chips_display = FluentChipsDisplay(self, self._theme)
self._chips_display.setPlaceholderText(self._placeholder_text)
self._chips_display.chipRemoved.connect(self._on_chip_removed)
self._chips_display.clicked.connect(self._on_chips_clicked)
# Position the chips display over the line edit
self._update_chips_geometry()
def _update_chips_geometry(self) -> None:
"""Update the chips display geometry to match the combo box."""
if self._chips_display is None:
return
# Leave space for the dropdown arrow
rect = self.rect()
chips_rect = rect.adjusted(1, 1, -30, -1)
self._chips_display.setGeometry(chips_rect)
def _on_chip_removed(self, row_idx: int) -> None:
"""Handle chip removal by unchecking the item."""
self.setItemChecked(row_idx, False)
def _on_chips_clicked(self) -> None:
"""Handle click on chips display to toggle popup."""
if self._popup_visible:
self.hidePopup()
else:
self.showPopup()
# ==================== Properties ====================
@pyqtProperty(float)
def arrowRotation(self) -> float:
"""Get the current arrow rotation angle."""
return self._arrow_rotation
@arrowRotation.setter
def arrowRotation(self, value: float) -> None:
"""Set the arrow rotation angle."""
self._arrow_rotation = value
self.update()
# ==================== Theme ====================
def _apply_theme(self) -> None:
"""Apply the current theme styling."""
self._delegate.setTheme(self._theme)
self.setStyleSheet(FluentStyleSheet.get_combo_box_style(self._theme))
self.view().setStyleSheet(FluentStyleSheet.get_popup_style(self._theme))
if self._chips_display is not None:
self._chips_display.setTheme(self._theme)
self.update()
def setTheme(self, theme: Theme) -> None:
"""
Set the theme for the combo box.
Args:
theme: The theme to apply (Theme.DARK or Theme.LIGHT).
"""
self._theme = theme
self._apply_theme()
def theme(self) -> Theme:
"""Get the current theme."""
return self._theme
# ==================== Chips Display ====================
def setChipsEnabled(self, enabled: bool) -> None:
"""
Enable or disable the chips display mode.
When enabled, selected items are shown as chips with X buttons
to remove them individually.
Args:
enabled: Whether to enable chips display.
Example:
combo.setChipsEnabled(True)
# Now selected items appear as removable chips
"""
self._chips_enabled = enabled
if enabled:
self._setup_chips_display()
self._chips_display.show()
self.lineEdit().hide()
else:
if self._chips_display is not None:
self._chips_display.hide()
self.lineEdit().show()
self.updateText()
def isChipsEnabled(self) -> bool:
"""
Check if chips display mode is enabled.
Returns:
True if chips are enabled, False otherwise.
"""
return self._chips_enabled
def setMaxVisibleChips(self, count: Optional[int]) -> None:
"""
Set maximum number of visible chips before showing overflow.
Args:
count: Maximum chips to display, or None for auto (based on width).
Example:
combo.setMaxVisibleChips(3) # Show max 3 chips, then "+N"
"""
if self._chips_display is not None:
self._chips_display.setMaxVisibleChips(count)
def maxVisibleChips(self) -> Optional[int]:
"""Get the maximum visible chips setting."""
if self._chips_display is not None:
return self._chips_display.maxVisibleChips()
return None
# ==================== Paint Events ====================
def _draw_focus_border(self, painter: QPainter, rect: QRect, color: QColor) -> None:
"""Draw the focus border based on configuration."""
if self._focus_border_position == "none":
return
if self._focus_border_position == "bottom":
focus_rect = QRectF(
rect.left() + 1,
rect.bottom() - self._focus_border_width,
rect.width() - 2,
self._focus_border_width,
)
focus_path = QPainterPath()
focus_path.addRoundedRect(focus_rect, 1, 1)
painter.fillPath(focus_path, color)
elif self._focus_border_position == "all":
painter.setPen(QPen(color, self._focus_border_width))
border_path = QPainterPath()
border_path.addRoundedRect(QRectF(rect.adjusted(1, 1, -1, -1)), 5, 5)
painter.drawPath(border_path)
def paintEvent(self, event: QPaintEvent) -> None:
"""Custom paint event for Fluent Design styling."""
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
colors = self._get_state_colors()
rect = self.rect()
# Background
path = QPainterPath()
path.addRoundedRect(QRectF(rect.adjusted(0, 0, -1, -1)), 5, 5)
painter.fillPath(path, colors["background"])
painter.setPen(QPen(colors["border"], 1))
painter.drawPath(path)
# Focus border
if self._focus_border_enabled and (self.hasFocus() or self._popup_visible):
self._draw_focus_border(painter, rect, colors["accent"])
# Arrow
self._draw_arrow(painter, rect, colors["arrow"])
def _get_state_colors(self) -> dict:
"""Get colors based on current state and theme."""
if self._theme == Theme.DARK:
if not self.isEnabled():
bg = QColor(255, 255, 255, 11)
border = QColor(255, 255, 255, 14)
elif self._pressed:
bg = QColor(255, 255, 255, 8)
border = QColor(255, 255, 255, 14)
elif self._hovered:
bg = QColor(255, 255, 255, 21)
border = QColor(255, 255, 255, 21)
else:
bg = QColor(255, 255, 255, 15)
border = QColor(255, 255, 255, 14)
return {
"background": bg,
"border": border,
"accent": FluentColors.DARK_ACCENT,
"arrow": QColor(255, 255, 255, 200),
}
else:
if not self.isEnabled():
bg = QColor(249, 249, 249, 77)
border = QColor(0, 0, 0, 15)
elif self._pressed:
bg = QColor(249, 249, 249, 77)
border = QColor(0, 0, 0, 15)
elif self._hovered:
bg = QColor(249, 249, 249, 128)
border = QColor(0, 0, 0, 19)
else:
bg = QColor(255, 255, 255, 179)
border = QColor(0, 0, 0, 19)
return {
"background": bg,
"border": border,
"accent": FluentColors.LIGHT_ACCENT,
"arrow": QColor(0, 0, 0, 200),
}
def _draw_arrow(self, painter: QPainter, rect: QRect, color: QColor) -> None:
"""Draw the dropdown arrow."""
painter.save()
arrow_size = 10
arrow_x = rect.right() - 20
arrow_y = rect.center().y()
painter.translate(arrow_x, arrow_y)
painter.rotate(self._arrow_rotation)
painter.setPen(
QPen(
color,
1.5,
Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap,
Qt.PenJoinStyle.RoundJoin,
)
)
path = QPainterPath()
path.moveTo(-arrow_size / 2, -arrow_size / 4)
path.lineTo(0, arrow_size / 4)
path.lineTo(arrow_size / 2, -arrow_size / 4)
painter.drawPath(path)
painter.restore()
# ==================== Event Handlers ====================
def enterEvent(self, event: QEnterEvent) -> None:
"""Handle mouse enter."""
self._hovered = True
self.update()
super().enterEvent(event)
def leaveEvent(self, event: QEvent) -> None:
"""Handle mouse leave."""
self._hovered = False
self.update()
super().leaveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None:
"""Handle mouse press."""
self._pressed = True
self.update()
super().mousePressEvent(event)
def mouseReleaseEvent(self, event: QMouseEvent) -> None:
"""Handle mouse release."""
self._pressed = False
self.update()
# Only toggle popup if not clicking on chips
if self._chips_enabled and self._chips_display is not None:
# Let chips handle their own clicks
chips_rect = self._chips_display.geometry()
if chips_rect.contains(event.pos()):
return
if self._popup_visible:
self.hidePopup()
else:
self.showPopup()
def wheelEvent(self, event: QWheelEvent) -> None:
"""Ignore wheel events to prevent changing selection by scrolling."""
if self._popup_visible:
self.view().wheelEvent(event)
else:
event.ignore()
def keyPressEvent(self, event: QKeyEvent) -> None:
"""Handle key press events."""
key = event.key()
if key == Qt.Key.Key_Escape and self._popup_visible:
self.hidePopup()
event.accept()
return
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Space):
if not self._popup_visible:
self.showPopup()
event.accept()
return
super().keyPressEvent(event)
def showPopup(self) -> None:
"""Show the popup with animation."""
self._popup_visible = True
self._arrow_animation.stop()
self._arrow_animation.setStartValue(self._arrow_rotation)
self._arrow_animation.setEndValue(180)
self._arrow_animation.start()
view = self.view()
shadow = QGraphicsDropShadowEffect(view)
shadow.setBlurRadius(16)
shadow.setOffset(0, 4)
shadow_alpha = 80 if self._theme == Theme.DARK else 40
shadow.setColor(QColor(0, 0, 0, shadow_alpha))
view.setGraphicsEffect(shadow)
super().showPopup()
self.update()
def hidePopup(self) -> None:
"""Hide the popup with animation."""
self._popup_visible = False
self._arrow_animation.stop()
self._arrow_animation.setStartValue(self._arrow_rotation)
self._arrow_animation.setEndValue(0)
self._arrow_animation.start()
super().hidePopup()
self.update()
def resizeEvent(self, event) -> None:
"""Handle resize events."""
super().resizeEvent(event)
self._update_chips_geometry()
self.updateText()
def setModel(self, model: QAbstractItemModel) -> None:
"""Override to reconnect model signals."""
old_model = self.model()
if old_model:
self._disconnect_model_signals(old_model)
super().setModel(model)
self._connect_model_signals(model)
self._rebuild_checked_cache()
self.updateText()
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
"""Handle events for child widgets."""
event_type = event.type()
# Line edit events (only when chips not enabled)
if obj == self.lineEdit() and not self._chips_enabled:
if event_type == QEvent.Type.MouseButtonRelease:
if self._popup_visible:
self.hidePopup()
else:
self.showPopup()
return True
elif event_type == QEvent.Type.KeyPress:
self.keyPressEvent(event)
return True
# View viewport click
if obj == self.view().viewport():
if event_type == QEvent.Type.MouseButtonRelease:
pos = event.position().toPoint()
index = self.view().indexAt(pos)
if index.isValid():
self._toggle_item(index.row())
return True