-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidgets.py
More file actions
4764 lines (3902 loc) · 180 KB
/
widgets.py
File metadata and controls
4764 lines (3902 loc) · 180 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
# -*- coding: utf-8 -*-
import os
import subprocess
import logging
import sys
import json
import fnmatch
import re
from maya import cmds
try:
from PySide6 import QtWidgets, QtCore, QtGui # type: ignore
from PySide6.QtGui import QAction, QActionGroup # type: ignore
except ImportError:
from PySide2 import QtWidgets, QtCore, QtGui # type: ignore
from PySide2.QtWidgets import QAction, QActionGroup
from . import utils
from . import TOOL_TITLE
# -------------------- Logging --------------------
LOG = logging.getLogger(TOOL_TITLE)
CONTEXTUAL_CURSOR = QtGui.QCursor(QtGui.QPixmap(":/rmbMenu.png"), hotX=11, hotY=8)
# -------------------- Flow Layout --------------------
class FlowLayout(QtWidgets.QLayout):
"""Standard Qt FlowLayout implementation."""
def __init__(self, parent=None, margin=0, hSpacing=-1, vSpacing=-1):
super(FlowLayout, self).__init__(parent)
if parent is not None:
self.setContentsMargins(margin, margin, margin, margin)
self._hSpace = hSpacing
self._vSpace = vSpacing
self._itemList = []
def addItem(self, item):
self._itemList.append(item)
def addWidget(self, widget):
self.addItem(QtWidgets.QWidgetItem(widget))
widget.setParent(self.parentWidget())
self.invalidate()
def insertWidget(self, index, widget):
widget.setParent(self.parentWidget())
item = QtWidgets.QWidgetItem(widget)
self._itemList.insert(index, item)
self.invalidate()
def insertItem(self, index, item):
self._itemList.insert(index, item)
self.invalidate()
def horizontalSpacing(self):
if self._hSpace >= 0:
return self._hSpace
return self.smartSpacing(QtWidgets.QStyle.PM_LayoutHorizontalSpacing)
def verticalSpacing(self):
if self._vSpace >= 0:
return self._vSpace
return self.smartSpacing(QtWidgets.QStyle.PM_LayoutVerticalSpacing)
def count(self):
return len(self._itemList)
def itemAt(self, index):
if 0 <= index < len(self._itemList):
return self._itemList[index]
return None
def takeAt(self, index):
if 0 <= index < len(self._itemList):
return self._itemList.pop(index)
return None
def expandingDirections(self):
return QtCore.Qt.Orientations(QtCore.Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
return self.doLayout(QtCore.QRect(0, 0, width, 0), True)
def setGeometry(self, rect):
super(FlowLayout, self).setGeometry(rect)
self.doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
def minimumSize(self):
size = QtCore.QSize()
for item in self._itemList:
size = size.expandedTo(item.minimumSize())
size += QtCore.QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top())
return size
def doLayout(self, rect, testOnly):
x = rect.x()
y = rect.y()
lineHeight = 0
spacingX = self.horizontalSpacing()
spacingY = self.verticalSpacing()
for item in self._itemList:
wid = item.widget()
# Skip hidden widgets to prevent gaps
if wid and not wid.isVisible():
continue
spaceX = spacingX
spaceY = spacingY
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > rect.right() and lineHeight > 0:
x = rect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0
if not testOnly:
item.setGeometry(QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y()
def smartSpacing(self, pm):
parent = self.parent()
if parent is None:
return 10
elif parent.isWidgetType():
try:
return parent.style().pixelMetric(pm, None, parent)
except Exception:
return 10
else:
return parent.spacing()
# -------------------- Utility Widgets --------------------
class OpenMenu(QtWidgets.QMenu):
def __init__(self, title=None, parent=None):
super(OpenMenu, self).__init__(title, parent) if title else super(OpenMenu, self).__init__(parent)
self.setSeparatorsCollapsible(False)
if parent and hasattr(parent, "destroyed"):
parent.destroyed.connect(self.close)
self.triggered.connect(self._on_action_triggered)
def _on_action_triggered(self, action):
if isinstance(action, QtWidgets.QWidgetAction):
return
def showEvent(self, event):
self._show_time = QtCore.QDateTime.currentMSecsSinceEpoch()
self._show_pos = QtGui.QCursor.pos()
super(OpenMenu, self).showEvent(event)
def mouseReleaseEvent(self, e):
# Prevent accidental trigger if menu was just opened via QPushButton click
# Ignoring release if it's within 200ms and mouse hasn't moved much
if hasattr(self, "_show_time"):
time_diff = QtCore.QDateTime.currentMSecsSinceEpoch() - self._show_time
pos_diff = (QtGui.QCursor.pos() - self._show_pos).manhattanLength()
if time_diff < 200 and pos_diff < 5:
return
action = self.actionAt(e.pos())
if action and action.isEnabled():
action.setEnabled(False)
super(OpenMenu, self).mouseReleaseEvent(e)
action.setEnabled(True)
action.trigger()
else:
super(OpenMenu, self).mouseReleaseEvent(e)
class ClickableLabel(QtWidgets.QLabel):
clicked = QtCore.Signal()
def __init__(self, parent=None):
super(ClickableLabel, self).__init__(parent)
self.setFixedSize(148, 148)
self.setAlignment(QtCore.Qt.AlignCenter)
self.setStyleSheet("border: 1px solid #444; background: #222; color: #888;")
self._default_cursor = self.cursor()
self._clickable = False
def updateImageDisplay(self, object):
"""Standardizes image loading logic."""
img_name = object.data.get("image") or utils.get_image_filename(object.name)
img_path = os.path.join(utils.IMAGES_DIR, img_name)
if img_name and os.path.exists(img_path):
pix = QtGui.QPixmap(img_path)
self.setPixmap(
pix.scaled(
self.size(),
QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation,
)
)
self._clickable = False
self.setCursor(self._default_cursor)
else:
self.setPixmap(QtGui.QPixmap())
self.setText("{}\n(Click to set)".format(object.name))
self.setCursor(QtCore.Qt.PointingHandCursor)
self._clickable = True
def mousePressEvent(self, event):
if self._clickable and event.button() == QtCore.Qt.LeftButton:
self.clicked.emit()
super(ClickableLabel, self).mousePressEvent(event)
class ContextLabel(QtWidgets.QLabel):
"""A QLabel that provides a context menu to copy its text or tooltip."""
def __init__(self, text="", is_path=False, is_link=False, parent=None):
super(ContextLabel, self).__init__(text, parent)
self._is_path = is_path
self._is_link = is_link
self.setCursor(CONTEXTUAL_CURSOR)
if text:
self.setToolTip(text)
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
label = "Copy URL" if self._is_link else "Copy path" if self._is_path else "Copy"
copy_act = menu.addAction(label)
action = menu.exec_(self.mapToGlobal(event.pos()))
if action == copy_act:
# Prefer tooltip as it usually holds the full un-elided text
text_to_copy = self.toolTip() or self.text()
QtWidgets.QApplication.clipboard().setText(text_to_copy)
class LoadingDotsWidget(QtWidgets.QLabel):
"""A standalone widget that cycles through dots (. .. ...) for loading states."""
clicked = QtCore.Signal()
def __init__(self, parent=None):
super(LoadingDotsWidget, self).__init__(parent)
self._dots_count = 0
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(self._update_dots)
self.setFixedWidth(20) # Fixed width for 3 dots to avoid jitter
self.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.setStyleSheet("color: #888; margin: 0; padding: 0;") # Explicitly remove margins/padding
self.hide()
def start(self):
self._dots_count = 0
self._update_dots()
self._timer.start(500)
self.show()
def stop(self):
self._timer.stop()
self.hide()
def get_dots_text(self):
"""Returns the current dots combined with transparent spacers for layout consistency."""
dots = "." * self._dots_count
hidden = "." * (3 - self._dots_count)
return "{}<span style='color:transparent;'>{}</span>".format(dots, hidden)
def _update_dots(self):
self.setText(self.get_dots_text())
self._dots_count = (self._dots_count + 1) % 4
class ElidedLabel(ContextLabel):
"""A label that elides text from the left and provides a context menu."""
def __init__(self, text, is_path=False, is_link=False, color=None, parent=None):
super(ElidedLabel, self).__init__(text, is_path=is_path, is_link=is_link, parent=parent)
self._full_text = text
self._color = color
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
# Use contextual cursor to indicate right-click availability
self.setCursor(CONTEXTUAL_CURSOR)
def setText(self, text):
self._full_text = text
self.setToolTip(text)
self.updateGeometry()
self.update()
def minimumSizeHint(self):
return QtCore.QSize(10, super(ElidedLabel, self).minimumSizeHint().height())
def sizeHint(self):
fm = self.fontMetrics()
w = (
fm.horizontalAdvance(self._full_text)
if hasattr(fm, "horizontalAdvance")
else fm.width(self._full_text)
)
return QtCore.QSize(w, super(ElidedLabel, self).sizeHint().height())
def paintEvent(self, event):
painter = QtGui.QPainter(self)
metrics = painter.fontMetrics()
# Elide at the right (end)
elided = metrics.elidedText(self._full_text, QtCore.Qt.ElideRight, self.width())
if self._color:
painter.setPen(QtGui.QColor(self._color))
elif self._is_path or self._is_link:
painter.setPen(QtGui.QColor("#74accc"))
else:
painter.setPen(self.palette().color(QtGui.QPalette.WindowText))
# If elided, align left, otherwise use default alignment
align = self.alignment()
if elided != self._full_text:
align = QtCore.Qt.AlignLeft
painter.drawText(self.rect(), align | QtCore.Qt.AlignVCenter, elided)
class ElidedClickableLabel(ElidedLabel):
"""A version of ElidedLabel that adds a click signal and hand cursor."""
clicked = QtCore.Signal()
def __init__(self, text, is_path=False, is_link=False, color=None, parent=None):
super(ElidedClickableLabel, self).__init__(
text, is_path=is_path, is_link=is_link, color=color, parent=parent
)
self.setCursor(QtCore.Qt.PointingHandCursor)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.clicked.emit()
class ElidedButton(QtWidgets.QPushButton):
"""A QPushButton that elides its text if too long."""
def __init__(self, text="", parent=None):
super(ElidedButton, self).__init__(text, parent)
self._full_text = text
def setText(self, text):
self._full_text = text
super(ElidedButton, self).setText(text)
self.update()
def paintEvent(self, event):
# Build style options for standard button drawing
opt = QtWidgets.QStyleOptionButton()
self.initStyleOption(opt)
# Clear text from option so standard draw doesn't draw it
opt.text = ""
painter = QtWidgets.QStylePainter(self)
painter.drawControl(QtWidgets.QStyle.CE_PushButton, opt)
# Draw elided text manually
metrics = self.fontMetrics()
# Reserve space for chevron on the right (approx 24px)
available_w = self.width() - 28
elided = metrics.elidedText(self._full_text, QtCore.Qt.ElideRight, available_w)
# Inset text rect to match typical button padding
text_rect = self.rect().adjusted(6, 0, -24, 0)
# Alignment logic: left if elided, center otherwise
align = QtCore.Qt.AlignCenter
if elided != self._full_text:
align = QtCore.Qt.AlignLeft
painter.setPen(self.palette().color(QtGui.QPalette.ButtonText))
if not self.isEnabled():
painter.setPen(self.palette().color(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText))
painter.drawText(text_rect, align | QtCore.Qt.AlignVCenter, elided)
# Draw Chevron manually to ensure it's on the right & centered
icon_path = os.path.join(utils.ICONS_DIR, "chevron_down.svg")
if os.path.exists(icon_path):
pix = QtGui.QIcon(icon_path).pixmap(14, 14)
# Position at the right with a 6px margin, centered vertically
icon_x = self.width() - 14 - 6
icon_y = (self.height() - 14) / 2.0
# If button is hovered or pressed, optional: tint icon?
# For now just draw it as is
painter.drawPixmap(int(icon_x), int(icon_y), pix)
class EmptyStateWidget(QtWidgets.QWidget):
"""A pretty and professional empty state overlay for the grid."""
actionRequested = QtCore.Signal()
def __init__(self, parent=None):
super(EmptyStateWidget, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
self.setObjectName("EmptyStateWidget")
self.setStyleSheet("#EmptyStateWidget { background-color: transparent; }")
layout = QtWidgets.QVBoxLayout(self)
layout.setAlignment(QtCore.Qt.AlignCenter)
layout.setSpacing(20)
# Main Icon
self.icon_lbl = QtWidgets.QLabel()
self.icon_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.icon_lbl.setFixedSize(120, 120)
self.icon_lbl.setStyleSheet("color: #444; background: transparent;")
layout.addWidget(self.icon_lbl, 0, QtCore.Qt.AlignCenter)
# Title
self.title_lbl = QtWidgets.QLabel()
self.title_lbl.setStyleSheet("font-size: 18pt; font-weight: bold;")
self.title_lbl.setAlignment(QtCore.Qt.AlignCenter)
layout.addWidget(self.title_lbl)
# Description
self.desc_lbl = QtWidgets.QLabel()
self.desc_lbl.setStyleSheet("font-size: 11pt; color: #888;")
self.desc_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.desc_lbl.setWordWrap(True)
self.desc_lbl.setFixedWidth(350)
layout.addWidget(self.desc_lbl, 0, QtCore.Qt.AlignCenter)
# Action Button
self.btn = QtWidgets.QPushButton()
self.btn.setCursor(QtCore.Qt.PointingHandCursor)
self.btn.setFixedHeight(34)
self.btn.setFixedWidth(180)
# self.btn.setStyleSheet("""
# QPushButton {
# background-color: #555;
# color: #ddd;
# font-weight: bold;
# border: none;
# border-radius: 4px;
# padding: 0 20px;
# }
# QPushButton:hover { background-color: #666; color: #fff; }
# QPushButton:pressed { background-color: #444; }
# """)
self.btn.clicked.connect(self.actionRequested.emit)
layout.addWidget(self.btn, 0, QtCore.Qt.AlignCenter)
def set_no_results(self):
"""Configure for 'no search results found'."""
self.icon_lbl.setPixmap(utils.get_icon("search.svg").pixmap(100, 100))
self.title_lbl.setText("No matches found")
self.desc_lbl.setText("We couldn't find any rigs matching your current filters or search query.")
self.btn.setText("Clear All Filters")
self.btn.setIcon(utils.get_icon("trash.svg"))
self.btn.setVisible(True)
def set_empty_database(self):
"""Configure for 'completely empty library'."""
self.icon_lbl.setPixmap(utils.get_icon("info.svg").pixmap(100, 100))
self.title_lbl.setText("Library is empty")
# Added the user's specific requested text "bieatch"
self.desc_lbl.setText(
"It looks like you haven't added any rigs to your library yet. Use the [+] button to add rigs, bieatch!"
)
self.btn.setText("Add New Rig")
self.btn.setIcon(utils.get_icon("add.svg"))
self.btn.setVisible(True)
# -------------------- Scrollable Menu --------------------
class ScrollArrowButton(QtWidgets.QWidget):
"""Custom button for hover-based scrolling in ScrollableMenu."""
def __init__(self, arrow_type, menu):
super(ScrollArrowButton, self).__init__(menu)
self.arrow_type = arrow_type
self.menu = menu
self.setFixedHeight(20) # Increased for better icon visibility
self.setMouseTracking(True)
self.hovered = False
self.pressed = False
self.hide()
# Load icon
icon_name = "chevron_up.svg" if arrow_type == QtCore.Qt.UpArrow else "chevron_down.svg"
self._pixmap = QtGui.QPixmap(os.path.join(utils.ICONS_DIR, icon_name))
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
# Semi-transparent overlay background
if self.pressed:
bg_color = QtGui.QColor(35, 35, 35, 230)
elif self.hovered:
bg_color = QtGui.QColor(65, 65, 65, 230)
else:
bg_color = QtGui.QColor(40, 40, 40, 180) # Slightly transparent
painter.fillRect(self.rect(), bg_color)
# Draw Chevron Path manually for maximum quality
painter.setPen(
QtGui.QPen(
QtGui.QColor(180, 180, 180),
2.0,
QtCore.Qt.SolidLine,
QtCore.Qt.RoundCap,
QtCore.Qt.RoundJoin,
)
)
cx = self.width() / 2.0
cy = self.height() / 2.0
size = 4.5 # Slightly smaller to avoid edges
path = QtGui.QPainterPath()
if self.arrow_type == QtCore.Qt.UpArrow:
# Up Chevron - perfectly centered
path.moveTo(cx - size, cy + size * 0.35)
path.lineTo(cx, cy - size * 0.35)
path.lineTo(cx + size, cy + size * 0.35)
else:
# Down Chevron - perfectly centered
path.moveTo(cx - size, cy - size * 0.35)
path.lineTo(cx, cy + size * 0.35)
path.lineTo(cx + size, cy - size * 0.35)
painter.drawPath(path)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.pressed = True
self.update()
super(ScrollArrowButton, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.pressed = False
self.update()
vbar = self.menu._scroll_area.verticalScrollBar()
if self.arrow_type == QtCore.Qt.UpArrow:
vbar.setValue(0)
else:
vbar.setValue(vbar.maximum())
self.menu._update_arrows()
return
super(ScrollArrowButton, self).mouseReleaseEvent(event)
def enterEvent(self, event):
self.hovered = True
self.menu._start_scroll(-1 if self.arrow_type == QtCore.Qt.UpArrow else 1)
self.update()
def leaveEvent(self, event):
self.hovered = False
self.menu._stop_scroll()
self.update()
class ScrollContainer(QtWidgets.QWidget):
"""Container that positions scroll arrows as overlays to prevent layout jiggle."""
def __init__(self, scroll_area, up_btn, down_btn):
super(ScrollContainer, self).__init__()
self.scroll_area = scroll_area
self.up_btn = up_btn
self.down_btn = down_btn
self.up_btn.setParent(self)
self.down_btn.setParent(self)
layout = QtWidgets.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(self.scroll_area)
def resizeEvent(self, event):
super(ScrollContainer, self).resizeEvent(event)
w = self.width()
h = self.height()
self.up_btn.setGeometry(0, 0, w, 20)
self.down_btn.setGeometry(0, h - 20, w, 20)
self.up_btn.raise_()
self.down_btn.raise_()
class MenuItemWidget(QtWidgets.QWidget):
"""Custom widget representing a single checkable menu item within ScrollableMenu."""
# Easily changeable layout values
WIDGET_HEIGHT = 20
CHECKBOX_SIZE = 12
CONTENT_PADDING = 6
EXTRA_LEFT_MARGIN = 1 # Added left margin to match look of Maya
def __init__(self, action, menu):
super(MenuItemWidget, self).__init__()
self.action = action
self.menu = menu
self._hovered = False
self.setFixedHeight(self.WIDGET_HEIGHT)
self.setMouseTracking(True)
if self.action:
self.action.changed.connect(self.update)
self.action.toggled.connect(lambda _: self.update())
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
h = float(self.WIDGET_HEIGHT)
cs = float(self.CHECKBOX_SIZE)
margin_y = (h - cs) / 2.0
margin_x = margin_y + self.EXTRA_LEFT_MARGIN
# Column width shifts to accommodate the extra pixel
column_w = int(h) + self.EXTRA_LEFT_MARGIN
# Define the two distinct areas
checkbox_bg_rect = self.rect()
checkbox_bg_rect.setWidth(column_w)
text_bg_rect = self.rect().adjusted(column_w, 0, 0, 0)
# Draw Checkbox Column Background
painter.fillRect(checkbox_bg_rect, QtGui.QColor(64, 64, 64))
# Draw Text Area Background
if self._hovered:
painter.fillRect(text_bg_rect, QtGui.QColor(82, 133, 166))
else:
painter.fillRect(text_bg_rect, QtGui.QColor(82, 82, 82))
# Checkbox
if self.action and self.action.isCheckable():
# Square checkbox centered vertically, shifted by margin_x horizontally
check_rect = QtCore.QRectF(margin_x, margin_y, cs, cs)
# Always dark, borderless background
painter.fillRect(check_rect, QtGui.QColor(43, 43, 43))
if self.action.isChecked():
# Draw white checkmark
painter.setPen(QtGui.QPen(QtGui.QColor(200, 200, 200), 1.8))
# Proportional checkmark points for scalability
lx = check_rect.x() + cs * 0.22
ly = check_rect.y() + cs * 0.5
mx = check_rect.x() + cs * 0.43
my = check_rect.y() + cs * 0.72
rx = check_rect.x() + cs * 0.78
ry = check_rect.y() + cs * 0.28
painter.drawLine(QtCore.QPointF(lx, ly), QtCore.QPointF(mx, my))
painter.drawLine(QtCore.QPointF(mx, my), QtCore.QPointF(rx, ry))
# Content (Icon + Text) starts after the checkbox column + padding
text_offset = column_w + self.CONTENT_PADDING
# Icon
icon = self.action.icon() if self.action else QtGui.QIcon()
if not icon.isNull():
icon_size = 16
icon_y = (h - icon_size) / 2.0
icon.paint(painter, QtCore.QRect(int(text_offset), int(icon_y), icon_size, icon_size))
text_offset += 24
# Text
text_color = QtGui.QColor(238, 238, 238)
painter.setPen(text_color)
font = (self.action.font() if self.action else self.font()) or self.font()
painter.setFont(font)
# Use a safe margin at the right
text_rect = self.rect().adjusted(int(text_offset), 0, -10, 0)
painter.drawText(
text_rect,
QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter,
self.get_text(),
)
def get_text(self):
return self.action.text() if self.action else ""
def enterEvent(self, event):
self._hovered = True
self.update()
def leaveEvent(self, event):
self._hovered = False
self.update()
def mouseReleaseEvent(self, event):
if not self.action:
return
if self.action.isCheckable():
self.action.setChecked(not self.action.isChecked())
else:
self.action.trigger()
self.menu.close()
def sizeHint(self):
fm = self.fontMetrics()
txt = self.get_text()
text_w = fm.horizontalAdvance(txt) if hasattr(fm, "horizontalAdvance") else fm.width(txt)
# Dynamic width: Checkbox Block (H+1) + Padding + (Icon Area if exists) + Text Width + Buffer
offset = self.WIDGET_HEIGHT + 1 + self.CONTENT_PADDING
icon = self.action.icon() if self.action else QtGui.QIcon()
if not icon.isNull():
offset += 24
return QtCore.QSize(text_w + int(offset) + 20, self.WIDGET_HEIGHT)
class ManageItemWidget(MenuItemWidget):
"""Custom widget for ScrollableMenu that mimics MenuItemWidget but adds a remove button."""
def __init__(self, text, remove_callback, menu):
super(ManageItemWidget, self).__init__(None, menu)
self._text = text
# Use a layout for the remove button to position it on the far right
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 4, 0)
layout.addStretch()
self.btn = QtWidgets.QPushButton()
self.btn.setIcon(utils.get_icon("remove.svg"))
self.btn.setIconSize(QtCore.QSize(10, 10))
self.btn.setFixedSize(16, 16)
self.btn.setCursor(QtCore.Qt.PointingHandCursor)
self.btn.setToolTip("Remove this instance")
self.btn.setStyleSheet("""
QPushButton { border: none; background: rgba(0, 0, 0, 0.2); border-radius: 8px; }
QPushButton:hover { background: rgba(255, 255, 255, 0.1); }
""")
self.btn.clicked.connect(remove_callback)
layout.addWidget(self.btn)
def get_text(self):
return self._text
class ScrollableMenu(OpenMenu):
"""
A QMenu that embeds a QScrollArea with hover-based scrolling arrows.
Used for long filter lists to avoid multiple columns.
"""
def __init__(self, title=None, parent=None):
super(ScrollableMenu, self).__init__(title, parent)
self._added_actions = []
# Remove QMenu internal padding and ensure full-width layout
self.setStyleSheet("QMenu { background: #404040; padding: 0px; }")
self.setContentsMargins(0, 0, 0, 0)
self._scroll_area = QtWidgets.QScrollArea()
self._scroll_area.setWidgetResizable(True)
self._scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
self._scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self._scroll_area.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
self._scroll_area.setContentsMargins(0, 0, 0, 0)
self._scroll_area.setMaximumHeight(600)
# Handle mouse wheel visibility
self._scroll_area.verticalScrollBar().valueChanged.connect(lambda _: self._update_arrows())
self._content_widget = QtWidgets.QWidget()
self._content_layout = QtWidgets.QVBoxLayout(self._content_widget)
self._content_layout.setContentsMargins(0, 0, 0, 0)
self._content_layout.setSpacing(0)
self._scroll_area.setWidget(self._content_widget)
self._up_btn = ScrollArrowButton(QtCore.Qt.UpArrow, self)
self._down_btn = ScrollArrowButton(QtCore.Qt.DownArrow, self)
self._container = ScrollContainer(self._scroll_area, self._up_btn, self._down_btn)
self._main_action = QtWidgets.QWidgetAction(self)
self._main_action.setDefaultWidget(self._container)
super(ScrollableMenu, self).addAction(self._main_action)
self._scroll_timer = QtCore.QTimer(self)
self._scroll_timer.timeout.connect(self._do_scroll)
self._scroll_speed = 0
def _start_scroll(self, direction):
self._scroll_speed = direction * 10
self._scroll_timer.start(16)
def _stop_scroll(self):
self._scroll_timer.stop()
def _do_scroll(self):
vbar = self._scroll_area.verticalScrollBar()
vbar.setValue(vbar.value() + self._scroll_speed)
self._update_arrows()
def _update_arrows(self):
vbar = self._scroll_area.verticalScrollBar()
self._up_btn.setVisible(vbar.value() > 0)
self._down_btn.setVisible(vbar.value() < vbar.maximum())
def addAction(self, action):
if isinstance(action, str):
action = QAction(action, self)
if not isinstance(action, QtWidgets.QWidgetAction):
self._added_actions.append(action)
wid = MenuItemWidget(action, self)
self._content_layout.addWidget(wid)
QtCore.QTimer.singleShot(0, self._update_arrows)
return action
return super(ScrollableMenu, self).addAction(action)
def addWidget(self, widget):
"""Adds a custom widget to the scrollable content layout."""
self._content_layout.addWidget(widget)
QtCore.QTimer.singleShot(0, self._update_arrows)
def addSection(self, text):
lbl = QtWidgets.QLabel(text)
lbl.setFixedHeight(MenuItemWidget.WIDGET_HEIGHT + MenuItemWidget.EXTRA_LEFT_MARGIN)
lbl.setStyleSheet(
"font-weight: bold; "
"background-color: #353535; " # Darker than menu's #444
"color: #9f9f9f; "
"padding-left: 10px;"
)
self._content_layout.addWidget(lbl)
return lbl
def addSeparator(self):
line = QtWidgets.QFrame()
line.setFrameShape(QtWidgets.QFrame.HLine)
line.setFrameShadow(QtWidgets.QFrame.Sunken)
line.setStyleSheet("background-color: #444; margin: 2px 0px; max-height: 1px;")
self._content_layout.addWidget(line)
def clear(self):
self._added_actions = []
while self._content_layout.count():
item = self._content_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
self._update_arrows()
def actions(self):
return self._added_actions
def sizeHint(self):
# Calculate Height based on content alone (arrows are overlayed)
self._content_layout.activate()
content_h = self._content_widget.sizeHint().height()
h = min(content_h, self._scroll_area.maximumHeight())
# Calculate Width: Match parent button width OR content width
w = 200
if self.parentWidget():
w = max(w, self.parentWidget().width())
# Check content width via action items
content_w = self._content_widget.sizeHint().width()
w = max(w, content_w + 10)
return QtCore.QSize(w, h)
def showEvent(self, event):
# Calculate and enforce size
hint = self.sizeHint()
self._container.setFixedSize(hint)
self.setFixedSize(hint)
super(ScrollableMenu, self).showEvent(event)
# Update arrows immediately
QtCore.QTimer.singleShot(0, self._update_arrows)
class FilterMenu(QtWidgets.QPushButton):
"""Button with a checkable menu for filtering."""
selectionChanged = QtCore.Signal()
def __init__(self, title, parent=None):
super(FilterMenu, self).__init__(title, parent)
self.menu = ScrollableMenu(parent=self)
self.setMenu(self.menu)
self._base_title = title
self._update_button_text()
def set_items(self, sections):
self.menu.clear()
if isinstance(sections, dict):
for section_name in sections.keys():
items = sections[section_name]
self.menu.addSection(section_name)
for item in items:
action = QAction(item, self.menu)
action.setData({"section": section_name, "value": item})
if item == "Empty":
font = action.font()
font.setItalic(True)
action.setFont(font)
action.setCheckable(True)
action.toggled.connect(self._on_change)
self.menu.addAction(action)
self.menu.addSeparator()
clear_action = QAction("Clear Filters", self.menu)
clear_action.setIcon(utils.get_icon("trash.svg"))
clear_action.triggered.connect(self.clear_selection)
self.menu.addAction(clear_action)
self._update_button_text()
def _on_change(self, checked):
self._update_button_text()
self.selectionChanged.emit()
def clear_selection(self):
valid = False
for action in self.menu.actions():
if action.isCheckable() and action.isChecked():
action.blockSignals(True)
action.setChecked(False)
action.blockSignals(False)
valid = True
if valid:
self._update_button_text()
self.selectionChanged.emit()
def get_selected(self):
selected = {}
for action in self.menu.actions():
if action.isCheckable() and action.isChecked():
data = action.data()
if data and isinstance(data, dict):
section = data.get("section")
value = data.get("value")
if section:
if section not in selected:
selected[section] = []
selected[section].append(value)
return selected
def set_selected(self, selected):
if not isinstance(selected, dict):
return
for action in self.menu.actions():
if action.isCheckable():
data = action.data()
if data and isinstance(data, dict):
section = data.get("section")
value = data.get("value")
should_check = False
if section and section in selected and value in selected[section]:
should_check = True
if action.isChecked() != should_check:
action.blockSignals(True)
action.setChecked(should_check)
action.blockSignals(False)
self._update_button_text()
def _update_button_text(self):
selected = self.get_selected()
count = sum(len(vals) for vals in selected.values())
self.setText("{} ({})".format(self._base_title, count))
class SortMenu(QtWidgets.QPushButton):
"""Button with a menu for sorting options."""
sortChanged = QtCore.Signal(str, bool) # key, ascending
def __init__(self, title="Sort", parent=None):
super(SortMenu, self).__init__(title, parent)
self.menu = OpenMenu(parent=self)
self.setMenu(self.menu)