Skip to content

drawers

AYONStyle drawer modules.

Each drawer handles custom QPainter-based painting for a specific Qt widget class, registered with the AYONStyle instance via register_drawers / register_sizers / register_metrics.

ButtonDrawer

Source code in client/ayon_core/ui/drawers/button.py
 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
class ButtonDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QPushButton": QPushButton}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_PushButton,
                "QPushButton",
            ): [
                partial(
                    self.style_inst.drawControl,
                    QStyle.ControlElement.CE_PushButtonBevel,
                ),
                partial(
                    self.style_inst.drawControl,
                    QStyle.ControlElement.CE_PushButtonLabel,
                ),
            ],
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_PushButtonBevel,
                "QPushButton",
            ): self.draw_push_button_bevel,
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_PushButtonLabel,
                "QPushButton",
            ): self.draw_push_button_label,
        }

    def register_sizers(self):
        return {
            enum_to_str(
                QStyle.ContentsType,
                QStyle.ContentsType.CT_PushButton,
                "QPushButton",
            ): self.calculate_push_button_size,
            enum_to_str(
                QStyle.SubElement,
                QStyle.SubElement.SE_PushButtonContents,
                "QPushButton",
            ): self.sub_element_rect,
            enum_to_str(
                QStyle.SubElement,
                QStyle.SubElement.SE_PushButtonFocusRect,
                "QPushButton",
            ): self.sub_element_rect,
        }

    def register_metrics(self):
        return {
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_ButtonMargin,
                "QPushButton",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_DefaultFrameWidth,
                "QPushButton",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_ButtonDefaultIndicator,
                "QPushButton",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_FocusFrameVMargin,
                "QPushButton",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_FocusFrameHMargin,
                "QPushButton",
            ): self.get_metric,
        }

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ):
        if metric == QStyle.PixelMetric.PM_ButtonMargin:
            return 6
        elif metric == QStyle.PixelMetric.PM_DefaultFrameWidth:
            return 0
        elif metric == QStyle.PixelMetric.PM_ButtonDefaultIndicator:
            return 0
        elif metric == QStyle.PixelMetric.PM_FocusFrameVMargin:
            return 2
        elif metric == QStyle.PixelMetric.PM_FocusFrameHMargin:
            return 2

    def get_button_variant(self, widget: QWidget) -> str:
        """Extract button variant from widget properties."""
        if widget is None:
            return "surface"
        return getattr(widget, "_variant_str", "surface")

    def get_button_has_icon(self, widget: QWidget) -> bool:
        """Check if button has an icon."""
        if widget is None:
            return False

        # Method 1: Try has_icon property
        if hasattr(widget, "has_icon"):
            return widget.has_icon  # type: ignore

        # Method 2: Try Qt property
        has_icon_prop = widget.property("has_icon")
        if has_icon_prop is not None:
            return bool(has_icon_prop)

        # Method 3: Check the actual icon
        return bool(widget.icon() and not widget.icon().isNull())  # type: ignore

    def get_button_style(
        self, widget: QWidget, state: QStyle.StateFlag
    ) -> tuple[dict, str]:
        """Get the appropriate style dictionary for the widget's variant and
        state."""
        variant = self.get_button_variant(widget)

        is_hover = bool(
            state & QStyle.StateFlag.State_MouseOver
        ) or widget.underMouse()

        wstate = "base"
        if not (state & QStyle.StateFlag.State_Enabled):
            wstate = "disabled"
        elif state & QStyle.StateFlag.State_Sunken:
            wstate = "pressed"
        elif is_hover and state & QStyle.StateFlag.State_On:
            # A checked button hovered stays on its checked colour, just
            # brighter. Falling back to the plain "hover" grey - which
            # this did unless a variant spelled out "checked-hover" -
            # dropped the only cue that the button is the active one.
            # A variant that defines no "checked-hover" resolves to
            # "checked", so the colour holds rather than turning grey.
            wstate = "checked-hover"
        elif is_hover:
            wstate = "hover"
        elif state & QStyle.StateFlag.State_On:
            wstate = "checked"

        style = self.model.get_style("QPushButton", variant, wstate)
        style.set_context(widget)

        return style, wstate

    def draw_push_button_bevel(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ) -> None:
        """Draw the button background and frame with hover detection."""
        option = _get_button_option(option, widget)
        if option is None or widget is None:
            return

        style, _ = self.get_button_style(widget, option.state)
        rect = option.rect

        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        # Draw button background with hover awareness
        # NOTE: QColor(...) wrapping is required here - PySide2's QBrush
        # constructor (unlike PySide6's) does not implicitly convert a
        # plain hex-color string, silently producing an invisible
        # NoBrush instead.
        bg_color = QColor(style["background-color"])
        painter.setOpacity(style.get("opacity", 1.0))

        painter.setBrush(QBrush(bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        border_radius = style.get("border-radius", 0)

        draw_icon_as_background = style.get("icon-as-background", False)
        clip_icon_to_radius = style.get("clip-icon-to-radius", False)

        if draw_icon_as_background:
            # draw the icon clipped by the same rounded rect
            painter.save()
            if clip_icon_to_radius:
                clip_path = QPainterPath()
                clip_path.addRoundedRect(rect, border_radius, border_radius)
                painter.setClipPath(clip_path)

            mode = QtGui.QIcon.Mode.Normal
            painter.drawRoundedRect(rect, border_radius, border_radius)
            option.icon.paint(
                painter,
                rect,
                Qt.AlignmentFlag.AlignCenter,
                mode,
            )

            if clip_icon_to_radius:
                painter.setClipping(False)

            pen = QPen(QColor(style.get("border-color")))
            pen.setWidth(int(style.get("border-width", 0)))
            painter.setPen(pen)
            painter.setBrush(Qt.BrushStyle.NoBrush)
            painter.drawRoundedRect(rect, border_radius, border_radius)
            painter.restore()
        else:
            painter.drawRoundedRect(rect, border_radius, border_radius)

        # Draw focus outline if needed
        if (
            option.state & QStyle.StateFlag.State_HasFocus
            and option.state  # type: ignore
            & QStyle.StateFlag.State_KeyboardFocusChange
        ):
            focus_color = style["focus-outline-color"]
            pen = QPen(
                QColor(focus_color), style.get("focus-outline-width", 0)
            )
            painter.setPen(pen)
            painter.setBrush(Qt.BrushStyle.NoBrush)
            focus_rect = rect.adjusted(1, 1, -1, -1)
            painter.drawRoundedRect(
                focus_rect, border_radius + 1, border_radius + 1
            )

        painter.restore()

    def draw_push_button_label(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ) -> None:
        """Draw the button text and icon."""
        option = _get_button_option(option, widget)
        if option is None or widget is None:
            return

        style, wstate = self.get_button_style(widget, option.state)  # type: ignore
        variant = self.get_button_variant(widget)

        # Set up text color
        text_color = self.model.get_widget_color(
            "color",
            style,
            widget,
            widget.palette().color(QPalette.ColorRole.ButtonText),
        )
        if not (option.state & QStyle.StateFlag.State_Enabled):  # type: ignore
            # Apply some opacity to disabled text
            text_color.setAlpha(int(255 * 0.5))

        painter.save()
        painter.setPen(text_color)

        # Set up font
        painter.setFont(widget.font())

        # Get content rectangle
        content_rect = self.style_inst.subElementRect(
            QStyle.SubElement.SE_PushButtonContents, option, widget
        )

        # Optional per-widget alignment override (None → default centered
        # layout)
        label_alignment = getattr(widget, "_label_alignment", None)

        if not option.icon:  # type: ignore
            # Text only
            if option.text and not style.get("ignore-text", False):  # type: ignore
                _text_align = (
                    (label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask)
                    | Qt.AlignmentFlag.AlignVCenter
                    if label_alignment is not None
                    else Qt.AlignmentFlag.AlignCenter
                )
                painter.drawText(
                    content_rect,
                    _text_align,
                    option.text,  # type: ignore
                )
            painter.restore()
            return

        # Draw icon if present
        if option.text and not style.get("ignore-text", False):  # type: ignore
            icon_size = option.iconSize  # type: ignore
            icon_w = icon_size.width()
            icon_h = icon_size.height()
            _gap = 4

            # Draw icon with text color inheritance
            mode = QtGui.QIcon.Mode.Normal
            if not (
                option.state & QStyle.StateFlag.State_Enabled  # type: ignore
            ):
                mode = QtGui.QIcon.Mode.Disabled
            elif option.state & QStyle.StateFlag.State_Sunken:  # type: ignore
                mode = QtGui.QIcon.Mode.Active

            # Same On/Off-as-hover encoding the icon-only branch below
            # uses: AYButton.set_icon() bakes the hover color into the
            # icon's "On" state for non-checkable buttons. Without
            # selecting that state here, an icon+text button's icon
            # never picks up its hover color even though the text does.
            checkable = widget.isCheckable() if widget else False
            icon_state = (
                (
                    QtGui.QIcon.State.On
                    if wstate == "hover"
                    else QtGui.QIcon.State.Off
                )
                if not checkable
                else (
                    QtGui.QIcon.State.On
                    if option.state & QStyle.StateFlag.State_On  # type: ignore
                    else QtGui.QIcon.State.Off
                )
            )

            if label_alignment is not None:
                # Group layout: icon + text move together as a unit
                h_align = (
                    label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask
                )
                text_w = painter.fontMetrics().horizontalAdvance(
                    option.text  # type: ignore
                )
                group_w = icon_w + _gap + text_w
                if h_align == Qt.AlignmentFlag.AlignLeft:
                    group_x = content_rect.left()
                elif h_align == Qt.AlignmentFlag.AlignRight:
                    group_x = content_rect.right() - group_w
                else:
                    group_x = (
                        content_rect.left()
                        + (content_rect.width() - group_w) // 2
                    )
                icon_rect = QRect(
                    group_x,
                    content_rect.center().y() - icon_h // 2,
                    icon_w,
                    icon_h,
                )
                text_rect = QRect(
                    icon_rect.right() + _gap,
                    content_rect.top(),
                    text_w,
                    content_rect.height(),
                )
                option.icon.paint(  # type: ignore
                    painter,
                    icon_rect,
                    Qt.AlignmentFlag.AlignCenter,
                    mode,
                    icon_state,
                )
                painter.drawText(
                    text_rect,
                    Qt.AlignmentFlag.AlignLeft
                    | Qt.AlignmentFlag.AlignVCenter,
                    option.text,  # type: ignore
                )
            else:
                # Icon + text: place icon on the left (default centered)
                icon_rect = QRect(content_rect)
                icon_rect.setSize(icon_size)
                icon_rect.moveCenter(
                    QtCore.QPoint(
                        content_rect.left() + style["icon-padding"][0],
                        content_rect.center().y(),
                    )
                )
                option.icon.paint(  # type: ignore
                    painter,
                    icon_rect,
                    Qt.AlignmentFlag.AlignCenter,
                    mode,
                    icon_state,
                )
                # Adjust text rectangle
                text_rect = QRect(content_rect)
                text_rect.setLeft(icon_rect.right() + _gap)
                # Draw text
                painter.drawText(
                    text_rect,
                    Qt.AlignmentFlag.AlignLeft
                    | Qt.AlignmentFlag.AlignVCenter,
                    option.text,  # type: ignore
                )
        elif variant not in ("thumbnail", "entity-card"):
            # Icon only
            mode = QtGui.QIcon.Mode.Normal
            if not (
                option.state & QStyle.StateFlag.State_Enabled  # type: ignore
            ):
                mode = QtGui.QIcon.Mode.Disabled
            elif option.state & QStyle.StateFlag.State_Sunken:  # type: ignore
                mode = QtGui.QIcon.Mode.Active

            checkable = widget.isCheckable() if widget else False

            icon_state = (
                (
                    QtGui.QIcon.State.On
                    if wstate == "hover"
                    else QtGui.QIcon.State.Off
                )
                if not checkable
                else (
                    QtGui.QIcon.State.On
                    if option.state & QStyle.StateFlag.State_On
                    else QtGui.QIcon.State.Off
                )
            )

            _icon_align = (
                (label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask)
                | Qt.AlignmentFlag.AlignVCenter
                if label_alignment is not None
                else Qt.AlignmentFlag.AlignCenter
            )
            option.icon.paint(  # type: ignore
                painter,
                content_rect,
                _icon_align,
                mode,
                icon_state,
            )

        painter.restore()

    def calculate_push_button_size(
        self,
        contents_type: QStyle.ContentsType,
        option: QStyleOption | None,
        contents_size: QtCore.QSize,
        widget: QWidget | None,
    ) -> QtCore.QSize:
        """Calculate minimum size for push buttons with text, icons,
        and proper padding."""

        button_option = _get_button_option(option, widget)
        if button_option is None:
            # Fallback to parent if we don't have proper option data
            if option is not None:
                return self._super.sizeFromContents(
                    contents_type,
                    option,
                    contents_size,
                    widget,
                )
            else:
                # Return reasonable default for button if no option
                return QtCore.QSize(100, 30)
        option = button_option

        # Set up font for text measurement
        style, _ = self.get_button_style(widget, option.state)  # type: ignore
        font = widget.font() if widget else style_font(style, widget)

        # Create font metrics for accurate text measurement
        font_metrics = QFontMetrics(font)

        # Determine if button has icon
        has_icon = (
            self.get_button_has_icon(widget)
            if widget
            else not option.icon.isNull()  # type: ignore
        )
        has_icon = not option.icon.isNull()

        # Determine appropriate padding
        if has_icon and not option.text:  # type: ignore
            # Icon-only button
            padding = style["icon-padding"]
        else:
            # Text button or icon+text button
            padding = style["text-padding"]

        # Calculate text dimensions
        text_width = 0
        text_height = 0
        if option.text and not style.get("ignore-text", False):  # type: ignore
            text_rect = font_metrics.boundingRect(option.text)  # type: ignore
            text_width = text_rect.width()
            text_height = text_rect.height()

        # Calculate icon dimensions
        icon_width = 0
        icon_height = 0
        if has_icon:
            icon_size = option.iconSize  # type: ignore
            icon_width = icon_size.width()
            icon_height = icon_size.height()

        # Calculate content dimensions
        content_width = 0
        content_height = 0

        if has_icon and option.text:  # type: ignore
            # Icon + text: icon on left, 4px spacing, then text
            content_width = icon_width + 4 + text_width
            content_height = max(icon_height, text_height)
        elif has_icon:
            # Icon only
            content_width = icon_width
            content_height = icon_height
        elif option.text:  # type: ignore
            # Text only
            content_width = text_width
            content_height = text_height

        # Add padding (vertical, horizontal)
        total_width = content_width + (
            2 * padding[1]
        )  # horizontal padding on both sides
        total_height = content_height + (
            2 * padding[0]
        )  # vertical padding on top and bottom

        # Ensure minimum button size (reasonable minimums)
        min_width = 16
        min_height = 16

        total_width = max(total_width, min_width)
        total_height = max(total_height, min_height)

        return QtCore.QSize(total_width, total_height)

    def sub_element_rect(
        self,
        element: QStyle.SubElement,
        option: QStyleOption,
        widget: QWidget,
    ):
        button_option = _get_button_option(option, widget)
        if button_option is None:
            raise ValueError("Button option could not be initialized")
        option = button_option
        if element == QStyle.SubElement.SE_PushButtonContents:
            style = self.model.get_style(
                "QPushButton", self.get_button_variant(widget)
            )
            style.set_context(widget)
            if option.icon:
                padding = (
                    style["icon-padding"]
                    if not widget.text()  # type: ignore
                    else style["text-padding"]
                )
            else:
                padding = style["text-padding"]

            return option.rect.adjusted(  # type: ignore
                padding[1], padding[0], -padding[1], -padding[0]
            )

        elif element == QStyle.SubElement.SE_PushButtonFocusRect:
            return option.rect.adjusted(-2, -2, 2, 2)  # type: ignore

        raise ValueError(f"Nothing returned ! -> {element}")

calculate_push_button_size(contents_type, option, contents_size, widget)

Calculate minimum size for push buttons with text, icons, and proper padding.

Source code in client/ayon_core/ui/drawers/button.py
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
def calculate_push_button_size(
    self,
    contents_type: QStyle.ContentsType,
    option: QStyleOption | None,
    contents_size: QtCore.QSize,
    widget: QWidget | None,
) -> QtCore.QSize:
    """Calculate minimum size for push buttons with text, icons,
    and proper padding."""

    button_option = _get_button_option(option, widget)
    if button_option is None:
        # Fallback to parent if we don't have proper option data
        if option is not None:
            return self._super.sizeFromContents(
                contents_type,
                option,
                contents_size,
                widget,
            )
        else:
            # Return reasonable default for button if no option
            return QtCore.QSize(100, 30)
    option = button_option

    # Set up font for text measurement
    style, _ = self.get_button_style(widget, option.state)  # type: ignore
    font = widget.font() if widget else style_font(style, widget)

    # Create font metrics for accurate text measurement
    font_metrics = QFontMetrics(font)

    # Determine if button has icon
    has_icon = (
        self.get_button_has_icon(widget)
        if widget
        else not option.icon.isNull()  # type: ignore
    )
    has_icon = not option.icon.isNull()

    # Determine appropriate padding
    if has_icon and not option.text:  # type: ignore
        # Icon-only button
        padding = style["icon-padding"]
    else:
        # Text button or icon+text button
        padding = style["text-padding"]

    # Calculate text dimensions
    text_width = 0
    text_height = 0
    if option.text and not style.get("ignore-text", False):  # type: ignore
        text_rect = font_metrics.boundingRect(option.text)  # type: ignore
        text_width = text_rect.width()
        text_height = text_rect.height()

    # Calculate icon dimensions
    icon_width = 0
    icon_height = 0
    if has_icon:
        icon_size = option.iconSize  # type: ignore
        icon_width = icon_size.width()
        icon_height = icon_size.height()

    # Calculate content dimensions
    content_width = 0
    content_height = 0

    if has_icon and option.text:  # type: ignore
        # Icon + text: icon on left, 4px spacing, then text
        content_width = icon_width + 4 + text_width
        content_height = max(icon_height, text_height)
    elif has_icon:
        # Icon only
        content_width = icon_width
        content_height = icon_height
    elif option.text:  # type: ignore
        # Text only
        content_width = text_width
        content_height = text_height

    # Add padding (vertical, horizontal)
    total_width = content_width + (
        2 * padding[1]
    )  # horizontal padding on both sides
    total_height = content_height + (
        2 * padding[0]
    )  # vertical padding on top and bottom

    # Ensure minimum button size (reasonable minimums)
    min_width = 16
    min_height = 16

    total_width = max(total_width, min_width)
    total_height = max(total_height, min_height)

    return QtCore.QSize(total_width, total_height)

draw_push_button_bevel(option, painter, widget)

Draw the button background and frame with hover detection.

Source code in client/ayon_core/ui/drawers/button.py
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
def draw_push_button_bevel(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None,
) -> None:
    """Draw the button background and frame with hover detection."""
    option = _get_button_option(option, widget)
    if option is None or widget is None:
        return

    style, _ = self.get_button_style(widget, option.state)
    rect = option.rect

    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)

    # Draw button background with hover awareness
    # NOTE: QColor(...) wrapping is required here - PySide2's QBrush
    # constructor (unlike PySide6's) does not implicitly convert a
    # plain hex-color string, silently producing an invisible
    # NoBrush instead.
    bg_color = QColor(style["background-color"])
    painter.setOpacity(style.get("opacity", 1.0))

    painter.setBrush(QBrush(bg_color))
    painter.setPen(Qt.PenStyle.NoPen)
    border_radius = style.get("border-radius", 0)

    draw_icon_as_background = style.get("icon-as-background", False)
    clip_icon_to_radius = style.get("clip-icon-to-radius", False)

    if draw_icon_as_background:
        # draw the icon clipped by the same rounded rect
        painter.save()
        if clip_icon_to_radius:
            clip_path = QPainterPath()
            clip_path.addRoundedRect(rect, border_radius, border_radius)
            painter.setClipPath(clip_path)

        mode = QtGui.QIcon.Mode.Normal
        painter.drawRoundedRect(rect, border_radius, border_radius)
        option.icon.paint(
            painter,
            rect,
            Qt.AlignmentFlag.AlignCenter,
            mode,
        )

        if clip_icon_to_radius:
            painter.setClipping(False)

        pen = QPen(QColor(style.get("border-color")))
        pen.setWidth(int(style.get("border-width", 0)))
        painter.setPen(pen)
        painter.setBrush(Qt.BrushStyle.NoBrush)
        painter.drawRoundedRect(rect, border_radius, border_radius)
        painter.restore()
    else:
        painter.drawRoundedRect(rect, border_radius, border_radius)

    # Draw focus outline if needed
    if (
        option.state & QStyle.StateFlag.State_HasFocus
        and option.state  # type: ignore
        & QStyle.StateFlag.State_KeyboardFocusChange
    ):
        focus_color = style["focus-outline-color"]
        pen = QPen(
            QColor(focus_color), style.get("focus-outline-width", 0)
        )
        painter.setPen(pen)
        painter.setBrush(Qt.BrushStyle.NoBrush)
        focus_rect = rect.adjusted(1, 1, -1, -1)
        painter.drawRoundedRect(
            focus_rect, border_radius + 1, border_radius + 1
        )

    painter.restore()

draw_push_button_label(option, painter, widget)

Draw the button text and icon.

Source code in client/ayon_core/ui/drawers/button.py
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
def draw_push_button_label(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None,
) -> None:
    """Draw the button text and icon."""
    option = _get_button_option(option, widget)
    if option is None or widget is None:
        return

    style, wstate = self.get_button_style(widget, option.state)  # type: ignore
    variant = self.get_button_variant(widget)

    # Set up text color
    text_color = self.model.get_widget_color(
        "color",
        style,
        widget,
        widget.palette().color(QPalette.ColorRole.ButtonText),
    )
    if not (option.state & QStyle.StateFlag.State_Enabled):  # type: ignore
        # Apply some opacity to disabled text
        text_color.setAlpha(int(255 * 0.5))

    painter.save()
    painter.setPen(text_color)

    # Set up font
    painter.setFont(widget.font())

    # Get content rectangle
    content_rect = self.style_inst.subElementRect(
        QStyle.SubElement.SE_PushButtonContents, option, widget
    )

    # Optional per-widget alignment override (None → default centered
    # layout)
    label_alignment = getattr(widget, "_label_alignment", None)

    if not option.icon:  # type: ignore
        # Text only
        if option.text and not style.get("ignore-text", False):  # type: ignore
            _text_align = (
                (label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask)
                | Qt.AlignmentFlag.AlignVCenter
                if label_alignment is not None
                else Qt.AlignmentFlag.AlignCenter
            )
            painter.drawText(
                content_rect,
                _text_align,
                option.text,  # type: ignore
            )
        painter.restore()
        return

    # Draw icon if present
    if option.text and not style.get("ignore-text", False):  # type: ignore
        icon_size = option.iconSize  # type: ignore
        icon_w = icon_size.width()
        icon_h = icon_size.height()
        _gap = 4

        # Draw icon with text color inheritance
        mode = QtGui.QIcon.Mode.Normal
        if not (
            option.state & QStyle.StateFlag.State_Enabled  # type: ignore
        ):
            mode = QtGui.QIcon.Mode.Disabled
        elif option.state & QStyle.StateFlag.State_Sunken:  # type: ignore
            mode = QtGui.QIcon.Mode.Active

        # Same On/Off-as-hover encoding the icon-only branch below
        # uses: AYButton.set_icon() bakes the hover color into the
        # icon's "On" state for non-checkable buttons. Without
        # selecting that state here, an icon+text button's icon
        # never picks up its hover color even though the text does.
        checkable = widget.isCheckable() if widget else False
        icon_state = (
            (
                QtGui.QIcon.State.On
                if wstate == "hover"
                else QtGui.QIcon.State.Off
            )
            if not checkable
            else (
                QtGui.QIcon.State.On
                if option.state & QStyle.StateFlag.State_On  # type: ignore
                else QtGui.QIcon.State.Off
            )
        )

        if label_alignment is not None:
            # Group layout: icon + text move together as a unit
            h_align = (
                label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask
            )
            text_w = painter.fontMetrics().horizontalAdvance(
                option.text  # type: ignore
            )
            group_w = icon_w + _gap + text_w
            if h_align == Qt.AlignmentFlag.AlignLeft:
                group_x = content_rect.left()
            elif h_align == Qt.AlignmentFlag.AlignRight:
                group_x = content_rect.right() - group_w
            else:
                group_x = (
                    content_rect.left()
                    + (content_rect.width() - group_w) // 2
                )
            icon_rect = QRect(
                group_x,
                content_rect.center().y() - icon_h // 2,
                icon_w,
                icon_h,
            )
            text_rect = QRect(
                icon_rect.right() + _gap,
                content_rect.top(),
                text_w,
                content_rect.height(),
            )
            option.icon.paint(  # type: ignore
                painter,
                icon_rect,
                Qt.AlignmentFlag.AlignCenter,
                mode,
                icon_state,
            )
            painter.drawText(
                text_rect,
                Qt.AlignmentFlag.AlignLeft
                | Qt.AlignmentFlag.AlignVCenter,
                option.text,  # type: ignore
            )
        else:
            # Icon + text: place icon on the left (default centered)
            icon_rect = QRect(content_rect)
            icon_rect.setSize(icon_size)
            icon_rect.moveCenter(
                QtCore.QPoint(
                    content_rect.left() + style["icon-padding"][0],
                    content_rect.center().y(),
                )
            )
            option.icon.paint(  # type: ignore
                painter,
                icon_rect,
                Qt.AlignmentFlag.AlignCenter,
                mode,
                icon_state,
            )
            # Adjust text rectangle
            text_rect = QRect(content_rect)
            text_rect.setLeft(icon_rect.right() + _gap)
            # Draw text
            painter.drawText(
                text_rect,
                Qt.AlignmentFlag.AlignLeft
                | Qt.AlignmentFlag.AlignVCenter,
                option.text,  # type: ignore
            )
    elif variant not in ("thumbnail", "entity-card"):
        # Icon only
        mode = QtGui.QIcon.Mode.Normal
        if not (
            option.state & QStyle.StateFlag.State_Enabled  # type: ignore
        ):
            mode = QtGui.QIcon.Mode.Disabled
        elif option.state & QStyle.StateFlag.State_Sunken:  # type: ignore
            mode = QtGui.QIcon.Mode.Active

        checkable = widget.isCheckable() if widget else False

        icon_state = (
            (
                QtGui.QIcon.State.On
                if wstate == "hover"
                else QtGui.QIcon.State.Off
            )
            if not checkable
            else (
                QtGui.QIcon.State.On
                if option.state & QStyle.StateFlag.State_On
                else QtGui.QIcon.State.Off
            )
        )

        _icon_align = (
            (label_alignment & Qt.AlignmentFlag.AlignHorizontal_Mask)
            | Qt.AlignmentFlag.AlignVCenter
            if label_alignment is not None
            else Qt.AlignmentFlag.AlignCenter
        )
        option.icon.paint(  # type: ignore
            painter,
            content_rect,
            _icon_align,
            mode,
            icon_state,
        )

    painter.restore()

get_button_has_icon(widget)

Check if button has an icon.

Source code in client/ayon_core/ui/drawers/button.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def get_button_has_icon(self, widget: QWidget) -> bool:
    """Check if button has an icon."""
    if widget is None:
        return False

    # Method 1: Try has_icon property
    if hasattr(widget, "has_icon"):
        return widget.has_icon  # type: ignore

    # Method 2: Try Qt property
    has_icon_prop = widget.property("has_icon")
    if has_icon_prop is not None:
        return bool(has_icon_prop)

    # Method 3: Check the actual icon
    return bool(widget.icon() and not widget.icon().isNull())  # type: ignore

get_button_style(widget, state)

Get the appropriate style dictionary for the widget's variant and state.

Source code in client/ayon_core/ui/drawers/button.py
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
def get_button_style(
    self, widget: QWidget, state: QStyle.StateFlag
) -> tuple[dict, str]:
    """Get the appropriate style dictionary for the widget's variant and
    state."""
    variant = self.get_button_variant(widget)

    is_hover = bool(
        state & QStyle.StateFlag.State_MouseOver
    ) or widget.underMouse()

    wstate = "base"
    if not (state & QStyle.StateFlag.State_Enabled):
        wstate = "disabled"
    elif state & QStyle.StateFlag.State_Sunken:
        wstate = "pressed"
    elif is_hover and state & QStyle.StateFlag.State_On:
        # A checked button hovered stays on its checked colour, just
        # brighter. Falling back to the plain "hover" grey - which
        # this did unless a variant spelled out "checked-hover" -
        # dropped the only cue that the button is the active one.
        # A variant that defines no "checked-hover" resolves to
        # "checked", so the colour holds rather than turning grey.
        wstate = "checked-hover"
    elif is_hover:
        wstate = "hover"
    elif state & QStyle.StateFlag.State_On:
        wstate = "checked"

    style = self.model.get_style("QPushButton", variant, wstate)
    style.set_context(widget)

    return style, wstate

get_button_variant(widget)

Extract button variant from widget properties.

Source code in client/ayon_core/ui/drawers/button.py
165
166
167
168
169
def get_button_variant(self, widget: QWidget) -> str:
    """Extract button variant from widget properties."""
    if widget is None:
        return "surface"
    return getattr(widget, "_variant_str", "surface")

CheckboxDrawer

Source code in client/ayon_core/ui/drawers/checkbox.py
 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
class CheckboxDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QCheckBox": QCheckBox}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_CheckBox,
                "QCheckBox",
            ): self.draw_indicator,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_IndicatorCheckBox,
                "QCheckBox",
            ): self.draw_toggle,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_FrameFocusRect,
                "QCheckBox",
            ): do_nothing,
        }

    def register_metrics(self):
        return {
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_IndicatorWidth,
                "QCheckBox",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_IndicatorHeight,
                "QCheckBox",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_CheckBoxLabelSpacing,
                "QCheckBox",
            ): self.get_metric,
        }

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ):
        variant = getattr(widget, "_variant_str", "default")
        style = self.model.get_style(
            "QCheckBox",
            variant=variant,
        )
        style.set_context(widget)
        metrics_h = widget.fontMetrics().height() if widget else 18
        metrics_w = metrics_h * 2 if widget else 32

        if metric == QStyle.PixelMetric.PM_IndicatorWidth:
            # if indicator-width == 0, use 2x the font height.
            return style.get("indicator-width", metrics_w) or metrics_w
        elif metric == QStyle.PixelMetric.PM_IndicatorHeight:
            # if indicator-height == 0, use the font height.
            return style.get("indicator-height", metrics_h) or metrics_h
        elif metric == QStyle.PixelMetric.PM_CheckBoxLabelSpacing:
            return style.get("checkbox-label-spacing", 8)
        return 0

    def draw_indicator(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ):
        variant = getattr(widget, "_variant_str", "default")
        state = (
            "checked" if option.state & QStyle.StateFlag.State_On else "base"
        )
        style = self.model.get_style(
            "QCheckBox",
            variant=variant,
            state=state,
        )
        style.set_context(widget)

        if style.get("background-color"):
            painter.save()
            painter.setBrush(QColor(style["background-color"]))
            painter.setPen(Qt.PenStyle.NoPen)
            radius = style.get("border-radius", 0)
            painter.drawRoundedRect(option.rect, radius, radius)
            painter.restore()

        if style.get("indicator-position", "left") == "right":
            # Manually draw a centred [label  toggle] group so that padding
            # is equal on both sides, instead of relying on Qt's layout.
            s = self.style_inst
            ind_w = s.pixelMetric(
                QStyle.PixelMetric.PM_IndicatorWidth, option, widget
            )
            ind_h = s.pixelMetric(
                QStyle.PixelMetric.PM_IndicatorHeight, option, widget
            )
            spacing = s.pixelMetric(
                QStyle.PixelMetric.PM_CheckBoxLabelSpacing, option, widget
            )

            text = getattr(option, "text", "")
            fm = option.fontMetrics
            text_w = fm.horizontalAdvance(text) if text else 0
            text_h = fm.height()

            total_w = text_w + (spacing + ind_w if text_w else ind_w)

            rect = option.rect
            cx = rect.center().x()
            cy = rect.center().y()
            x = cx - total_w // 2

            painter.save()
            if text:
                painter.setPen(
                    QColor(style["color"])
                    if style.get("color")
                    else option.palette.color(QPalette.ColorRole.WindowText)
                )
                text_rect = QRect(x, cy - text_h // 2, text_w, text_h)
                painter.drawText(
                    text_rect,
                    Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
                    text,
                )

            toggle_opt = QStyleOption(option)
            toggle_opt.rect = QRect(
                x + text_w + (spacing if text_w else 0),
                cy - ind_h // 2,
                ind_w,
                ind_h,
            )
            self.draw_toggle(toggle_opt, painter, widget)
            painter.restore()
            return

        if style.get("color"):
            option.palette.setColor(
                QPalette.ColorRole.WindowText, QColor(style["color"])
            )

        self._super.drawControl(
            QStyle.ControlElement.CE_CheckBox, option, painter, widget
        )

    def draw_toggle(
        self,
        option: QStyleOption,
        painter: QPainter,
        w: QWidget | None = None,
    ):
        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)

        # get style data
        checked = bool(option.state & QStyle.StateFlag.State_On)
        variant = getattr(w, "_variant_str", "default")
        styles = {}
        for state in ("base", "checked"):
            styles[state] = self.model.get_style(
                "QCheckBox", variant=variant, state=state
            )
            styles[state].set_context(w)
        style = styles["checked" if checked else "base"]

        # 0.0 is unchecked, 1.0 is checked; animated by the widget if it
        # supports it.
        progress = getattr(w, "_toggle_progress", 1.0 if checked else 0.0)

        def _color(key: str) -> QColor:
            base = styles["base"].get(key) or styles["checked"][key]
            checked_ = styles["checked"].get(key) or base
            return self._mix(QColor(base), QColor(checked_), progress)

        # draw toggle background
        painter.setBrush(_color("indicator-background-color"))
        if style.get("indicator-border-width", 0):
            pen = QPen(_color("indicator-border-color"))
            pen.setWidth(style.get("indicator-border-width", 0))
            painter.setPen(pen)
        else:
            painter.setPen(Qt.PenStyle.NoPen)
        frame_rect: QRectF = QRectF(option.rect).adjusted(1, 0, -1, 0)
        radius = frame_rect.height() / 2.0
        painter.drawRoundedRect(frame_rect, radius, radius)

        # draw toggle knob
        painter.setBrush(_color("indicator-color"))
        offset = frame_rect.height() * 0.125
        state_rect: QRectF = frame_rect.adjusted(
            offset, offset, -offset, -offset
        )
        state_rect.setWidth(state_rect.height())
        travel = frame_rect.width() - 2 * offset - state_rect.width()
        state_rect.moveLeft(state_rect.left() + travel * progress)
        painter.drawEllipse(state_rect)

        painter.restore()

    @staticmethod
    def _mix(color_a: QColor, color_b: QColor, ratio: float) -> QColor:
        """Linearly interpolate two colors (including alpha)."""
        if ratio <= 0.0:
            return color_a
        if ratio >= 1.0:
            return color_b
        return QColor.fromRgbF(
            *(
                a + (b - a) * ratio
                for a, b in zip(
                    color_a.getRgbF(), color_b.getRgbF()
                )
            )
        )

ComboBoxDrawer

Source code in client/ayon_core/ui/drawers/combobox.py
 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
class ComboBoxDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QComboBox": QComboBox}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_ComboBoxLabel,
                "QComboBox",
            ): self.draw_label,
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_ComboBox,
                "QComboBox",
            ): self.draw_box,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_PanelItemViewItem,
                "QFrame",
            ): self.draw_panel_item_view_item,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_FrameFocusRect,
                "QFrame",
            ): do_nothing,
        }

    def register_sizers(self):
        return {
            enum_to_str(
                QStyle.ContentsType,
                QStyle.ContentsType.CT_ComboBox,
                "QComboBox",
            ): self.combobox_size,
        }

    def get_fg_bg_colors(
        self,
        opt: QtWidgets.QStyleOptionComplex,
        w: QComboBox,
    ) -> tuple[QColor, QColor]:
        bg_color = opt.palette.color(
            QPalette.ColorGroup.Active, QPalette.ColorRole.Base
        )
        fg_color = opt.palette.color(
            QPalette.ColorGroup.Active, QPalette.ColorRole.ButtonText
        )

        inverted = getattr(w, "_inverted", False)
        current_index = w.currentIndex()
        if current_index >= 0:
            item_color = w.itemData(
                current_index, QtCore.Qt.ItemDataRole.ForegroundRole
            )
            if item_color is not None:
                item_color = item_color.color()
                fg_color = bg_color if inverted else item_color
                bg_color = item_color if inverted else bg_color

        return fg_color, bg_color

    def draw_box(
        self,
        opt: QtWidgets.QStyleOptionComplex,
        p: QPainter,
        w: QComboBox | None = None,
    ):
        if not isinstance(w, QComboBox):
            return

        state = (
            "hover"
            if (
                opt.state & QStyle.StateFlag.State_MouseOver
                or w.underMouse()
            )
            else "base"
        )
        _style = self.model.get_style(
            "QComboBox",
            variant=getattr(w, "_variant_str", None),
            state=state,
        )
        _style.set_context(w)
        style_bg_color = _style.get("background-color", None)
        opt.palette.setBrush(
            QPalette.ColorRole.Base,
            QColor(style_bg_color)
            if style_bg_color
            else self.model.base_palette.base(),
        )
        _radius = _style.get("border-radius", 0)

        if not w.isEditable():
            fg_color, bg_color = self.get_fg_bg_colors(opt, w)

            # Paint background with status color
            rect = opt.rect
            p.save()
            p.setBrush(QBrush(bg_color))
            p.setPen(QtCore.Qt.PenStyle.NoPen)
            p.drawRoundedRect(rect, _radius, _radius)
            p.restore()

            # Draw expand_more arrow if show_chevron is True
            show_chevron = getattr(w, "show_chevron", True)
            if show_chevron:
                arrow_rect = self._super.subControlRect(
                    QStyle.ComplexControl.CC_ComboBox,
                    opt,
                    QStyle.SubControl.SC_ComboBoxArrow,
                    w,
                )
                arrow_icon = get_icon("expand_more", fg_color)
                if arrow_icon and not arrow_rect.isEmpty():
                    arrow_size = min(arrow_rect.width(), arrow_rect.height())
                    pixmap = arrow_icon.pixmap(arrow_size, arrow_size)
                    popup_open = bool(opt.state & QStyle.StateFlag.State_On)
                    if popup_open:
                        pixmap = pixmap.transformed(QTransform().rotate(180))

                    px = (
                        arrow_rect.x()
                        + (arrow_rect.width() - arrow_size) // 2
                    )
                    py = (
                        arrow_rect.y()
                        + (arrow_rect.height() - arrow_size) // 2
                    )

                    p.drawPixmap(px, py, pixmap)

            # set pen for text drawing
            p.setPen(fg_color)
        else:
            # editable combobox - IMPLEMENT ME
            self._super.drawComplexControl(
                QStyle.ComplexControl.CC_ComboBox, opt, p, w
            )

    def draw_label(
        self,
        opt: QStyleOptionComboBox,
        p: QPainter,
        w: QWidget,
    ):
        if not isinstance(w, QComboBox):
            return

        _style = self.model.get_style(
            "QComboBox", variant=getattr(w, "_variant_str", None)
        )
        _style.set_context(w)
        icon_padding = _style.get("icon-padding", [4, 4])
        text_padding = _style.get("text-padding", [1, 1])

        fg_color, bg_color = self.get_fg_bg_colors(opt, w)

        base_cls = self._super
        edit_rect = base_cls.subControlRect(
            QStyle.ComplexControl.CC_ComboBox,
            opt,
            QStyle.SubControl.SC_ComboBoxEditField,
            w,
        )
        p.save()
        p.setClipRect(edit_rect)
        if opt.currentIcon:
            mode = (
                QIcon.Mode.Normal
                if opt.state & QStyle.StateFlag.State_Enabled
                else QIcon.Mode.Disabled
            )
            pixmap = opt.currentIcon.pixmap(opt.iconSize, mode)
            icon_rect = QRect(edit_rect)
            icon_rect.setWidth(opt.iconSize.width() + icon_padding[0])
            icon_rect.setHeight(opt.iconSize.height() + icon_padding[1])
            icon_rect = QStyle.alignedRect(
                opt.direction,
                Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
                icon_rect.size(),
                edit_rect,
            )
            if opt.editable:
                p.fillRect(
                    icon_rect, opt.palette.brush(QPalette.ColorRole.Base)
                )
            base_cls.drawItemPixmap(
                p, icon_rect, Qt.AlignmentFlag.AlignCenter, pixmap
            )
            if opt.direction == Qt.LayoutDirection.RightToLeft:
                edit_rect.translate(-icon_padding[0] - opt.iconSize.width(), 0)
            else:
                edit_rect.translate(opt.iconSize.width() + icon_padding[0], 0)

        if opt.currentText and not opt.editable:
            base_cls.drawItemText(
                p,
                edit_rect.adjusted(
                    text_padding[0],
                    -text_padding[1],
                    -text_padding[0],
                    text_padding[1],
                ),
                QStyle.visualAlignment(
                    opt.direction,
                    Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
                ),
                opt.palette,
                bool(opt.state & QStyle.StateFlag.State_Enabled),
                opt.currentText,
            )

        p.restore()

    def draw_panel_item_view_item(
        self, option: QStyleOption, painter: QPainter, w: QWidget
    ):
        cb = w.model().parent()
        if cb and getattr(cb, "_inverted", False):
            idx = option.index
            if idx:
                fgc = (
                    w.model().data(idx, Qt.ItemDataRole.ForegroundRole).color()
                )
                option.backgroundBrush.setColor(fgc)
        else:
            stl = self.model.get_style("QComboBox")
            stl.set_context(w)
            option.backgroundBrush.setColor(
                QColor(stl["menu-background-color"])
            )
        self._super.drawPrimitive(  # type: ignore
            QStyle.PrimitiveElement.PE_PanelItemViewItem, option, painter, w
        )

    def combobox_size(
        self,
        contents_type: QStyle.ContentsType,
        option: QStyleOption | None,
        contents_size: QtCore.QSize,
        widget: QWidget | None,
    ) -> QtCore.QSize:
        from qtpy.QtCore import QSize

        if not option or not isinstance(option, QStyleOptionComboBox):
            return QSize()

        style = self.model.get_style("QComboBox")
        style.set_context(widget)

        text_width = cb_height = 0
        if isinstance(widget, QComboBox):
            for i in range(widget.count()):
                t_rect = option.fontMetrics.boundingRect(
                    widget.itemData(i, Qt.ItemDataRole.DisplayRole)
                )
                text_width = max(text_width, t_rect.width())
                cb_height = max(cb_height, t_rect.height())

        text_width += style["text-padding"][0] * 2
        cb_height += style["text-padding"][1] * 2

        icon_width = 0
        if option.currentIcon:
            icon_size = getattr(widget, "_icon_size", 0)
            if icon_size == 0:
                all_sizes = option.currentIcon.availableSizes()
                icon_size = max(all_sizes[0].width(), all_sizes[0].height())
            icon_width = icon_size + style["icon-padding"][0] * 2
            icon_height = icon_size + style["icon-padding"][1] * 2
            cb_height = max(cb_height, icon_height)
            if text_width:
                icon_width += style["text-padding"][0]

        final_size = QSize(
            text_width + icon_width,
            min(getattr(widget, "_height", cb_height), cb_height),
        )
        return final_size

ItemViewItemDrawer

Drawer for item view items using QStyledItemDelegate.

Source code in client/ayon_core/ui/drawers/item_view.py
 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
class ItemViewItemDrawer:
    """Drawer for item view items using QStyledItemDelegate."""

    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def base_class(self):
        return {"QStyledItemDelegate": QStyledItemDelegate}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_ItemViewItem,
                "QStyledItemDelegate",
            ): self.draw_item_view_item,
        }

    def get_item_view_variant(self, widget: QWidget | None) -> str:
        """Extract item view variant from widget properties."""
        if widget is None:
            return "default"
        if hasattr(widget, "itemDelegate"):
            delegate = widget.itemDelegate()
            if hasattr(delegate, "_variant_str"):
                return delegate._variant_str
        return "default"

    def get_item_view_style(
        self,
        widget: QWidget | None,
        option: QStyleOptionViewItem,
    ) -> tuple[dict, str]:
        """Get the appropriate style dictionary for the widget's variant
        and state.

        Args:
            widget: The parent widget containing the item view.
            option: The style option containing state flags.

        Returns:
            A tuple of (style dictionary, state string).
        """
        variant = self.get_item_view_variant(widget)

        wstate = "base"
        is_checked = option.checkState == Qt.CheckState.Checked
        is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)

        if is_checked:
            wstate = "checked"
        elif is_hovered:
            wstate = "hover"

        style = self.model.get_style("QStyledItemDelegate", variant, wstate)
        style.set_context(widget)

        return style, wstate

    def draw_item_view_item(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ) -> None:
        """Paint a filter item with checkbox indicator.

        Hover and checked states are handled independently:
        - Background color comes from hover state when hovered
        - Checkbox background and text color come from checked state
        """
        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        # For QStyleOptionViewItem, we need to check different properties
        if not isinstance(option, QStyleOptionViewItem):
            painter.restore()
            return

        # Determine hover and checked states independently
        is_checked = option.checkState == Qt.CheckState.Checked
        is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
        text = option.text

        # Get variant for style lookups
        variant = self.get_item_view_variant(widget)

        # Get all necessary styles in a single call
        styles = self.model.get_styles(
            "QStyledItemDelegate", variant, ["base", "hover", "checked"]
        )
        base_style = styles["base"]
        hover_style = styles["hover"]
        checked_style = styles["checked"]

        # Constants from base style data
        checkbox_size = base_style.get("checkbox-size", 16)
        checkbox_margin = base_style.get("checkbox-margin", 8)
        text_padding = base_style.get("text-padding", 12)
        border_radius = base_style.get("border-radius", 2)

        # Background: use hover style if hovered, regardless of checked state
        if is_hovered:
            bg_color = QColor(
                hover_style.get(
                    "background-color",
                    base_style.get("background-color", "transparent"),
                )
            )
        else:
            bg_color = QColor(
                base_style.get("background-color", "transparent")
            )

        # Text color: use checked style if checked, else base
        if is_checked:
            text_color = QColor(
                checked_style.get("color", base_style.get("color", "#8b9198"))
            )
        else:
            text_color = QColor(base_style.get("color", "#8b9198"))

        # Checkbox background: use checked style if checked, else base
        if is_checked:
            checkbox_bg_color = QColor(
                checked_style.get(
                    "checkbox-background-color",
                    base_style.get("checkbox-background-color", "#424a57"),
                )
            )
        else:
            checkbox_bg_color = QColor(
                base_style.get("checkbox-background-color", "#424a57")
            )

        # Draw background if hovered
        if is_hovered:
            painter.setBrush(QBrush(bg_color))
            painter.setPen(Qt.PenStyle.NoPen)
            painter.drawRect(option.rect)

        # Calculate checkbox rect - positioned on right side
        cb_rect = QRect(
            option.rect.right() - checkbox_size - checkbox_margin,
            option.rect.center().y() - checkbox_size // 2,
            checkbox_size,
            checkbox_size,
        )

        # Draw checkbox background
        painter.setBrush(QBrush(checkbox_bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(cb_rect, border_radius, border_radius)

        # Draw X mark if checked
        if is_checked:
            icon = get_icon("close", color="#000000")
            icon_rect = cb_rect.adjusted(2, 2, -2, -2)
            icon.paint(painter, icon_rect)

        # Draw text
        painter.setPen(QPen(text_color))
        text_rect = option.rect.adjusted(
            text_padding,
            0,
            -(checkbox_size + checkbox_margin * 2),
            0,
        )
        painter.drawText(
            text_rect,
            Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
            text,
        )

        painter.restore()

draw_item_view_item(option, painter, widget)

Paint a filter item with checkbox indicator.

Hover and checked states are handled independently: - Background color comes from hover state when hovered - Checkbox background and text color come from checked state

Source code in client/ayon_core/ui/drawers/item_view.py
 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
def draw_item_view_item(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None,
) -> None:
    """Paint a filter item with checkbox indicator.

    Hover and checked states are handled independently:
    - Background color comes from hover state when hovered
    - Checkbox background and text color come from checked state
    """
    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)

    # For QStyleOptionViewItem, we need to check different properties
    if not isinstance(option, QStyleOptionViewItem):
        painter.restore()
        return

    # Determine hover and checked states independently
    is_checked = option.checkState == Qt.CheckState.Checked
    is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
    text = option.text

    # Get variant for style lookups
    variant = self.get_item_view_variant(widget)

    # Get all necessary styles in a single call
    styles = self.model.get_styles(
        "QStyledItemDelegate", variant, ["base", "hover", "checked"]
    )
    base_style = styles["base"]
    hover_style = styles["hover"]
    checked_style = styles["checked"]

    # Constants from base style data
    checkbox_size = base_style.get("checkbox-size", 16)
    checkbox_margin = base_style.get("checkbox-margin", 8)
    text_padding = base_style.get("text-padding", 12)
    border_radius = base_style.get("border-radius", 2)

    # Background: use hover style if hovered, regardless of checked state
    if is_hovered:
        bg_color = QColor(
            hover_style.get(
                "background-color",
                base_style.get("background-color", "transparent"),
            )
        )
    else:
        bg_color = QColor(
            base_style.get("background-color", "transparent")
        )

    # Text color: use checked style if checked, else base
    if is_checked:
        text_color = QColor(
            checked_style.get("color", base_style.get("color", "#8b9198"))
        )
    else:
        text_color = QColor(base_style.get("color", "#8b9198"))

    # Checkbox background: use checked style if checked, else base
    if is_checked:
        checkbox_bg_color = QColor(
            checked_style.get(
                "checkbox-background-color",
                base_style.get("checkbox-background-color", "#424a57"),
            )
        )
    else:
        checkbox_bg_color = QColor(
            base_style.get("checkbox-background-color", "#424a57")
        )

    # Draw background if hovered
    if is_hovered:
        painter.setBrush(QBrush(bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRect(option.rect)

    # Calculate checkbox rect - positioned on right side
    cb_rect = QRect(
        option.rect.right() - checkbox_size - checkbox_margin,
        option.rect.center().y() - checkbox_size // 2,
        checkbox_size,
        checkbox_size,
    )

    # Draw checkbox background
    painter.setBrush(QBrush(checkbox_bg_color))
    painter.setPen(Qt.PenStyle.NoPen)
    painter.drawRoundedRect(cb_rect, border_radius, border_radius)

    # Draw X mark if checked
    if is_checked:
        icon = get_icon("close", color="#000000")
        icon_rect = cb_rect.adjusted(2, 2, -2, -2)
        icon.paint(painter, icon_rect)

    # Draw text
    painter.setPen(QPen(text_color))
    text_rect = option.rect.adjusted(
        text_padding,
        0,
        -(checkbox_size + checkbox_margin * 2),
        0,
    )
    painter.drawText(
        text_rect,
        Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
        text,
    )

    painter.restore()

get_item_view_style(widget, option)

Get the appropriate style dictionary for the widget's variant and state.

Parameters:

Name Type Description Default
widget QWidget | None

The parent widget containing the item view.

required
option QStyleOptionViewItem

The style option containing state flags.

required

Returns:

Type Description
tuple[dict, str]

A tuple of (style dictionary, state string).

Source code in client/ayon_core/ui/drawers/item_view.py
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
def get_item_view_style(
    self,
    widget: QWidget | None,
    option: QStyleOptionViewItem,
) -> tuple[dict, str]:
    """Get the appropriate style dictionary for the widget's variant
    and state.

    Args:
        widget: The parent widget containing the item view.
        option: The style option containing state flags.

    Returns:
        A tuple of (style dictionary, state string).
    """
    variant = self.get_item_view_variant(widget)

    wstate = "base"
    is_checked = option.checkState == Qt.CheckState.Checked
    is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)

    if is_checked:
        wstate = "checked"
    elif is_hovered:
        wstate = "hover"

    style = self.model.get_style("QStyledItemDelegate", variant, wstate)
    style.set_context(widget)

    return style, wstate

get_item_view_variant(widget)

Extract item view variant from widget properties.

Source code in client/ayon_core/ui/drawers/item_view.py
43
44
45
46
47
48
49
50
51
def get_item_view_variant(self, widget: QWidget | None) -> str:
    """Extract item view variant from widget properties."""
    if widget is None:
        return "default"
    if hasattr(widget, "itemDelegate"):
        delegate = widget.itemDelegate()
        if hasattr(delegate, "_variant_str"):
            return delegate._variant_str
    return "default"

LineEditDrawer

AYONStyle drawer for QLineEdit.

Registers a no-op for PE_PanelLineEdit when the widget is an AYLineEdit instance (which paints itself fully in its own paintEvent), and falls back to the base QCommonStyle implementation for all other QLineEdit widgets.

Source code in client/ayon_core/ui/drawers/lineedit.py
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
class LineEditDrawer:
    """AYONStyle drawer for QLineEdit.

    Registers a no-op for PE_PanelLineEdit when the widget is an AYLineEdit
    instance (which paints itself fully in its own paintEvent), and falls back
    to the base QCommonStyle implementation for all other QLineEdit widgets.
    """

    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QLineEdit": QLineEdit}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_PanelLineEdit,
                "QLineEdit",
            ): self.draw_panel,
        }

    def draw_panel(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ) -> None:
        # AYLineEdit paints its own background — skip Qt's default frame.
        if type(widget).__name__ == "AYLineEdit":
            return
        self._super.drawPrimitive(
            QStyle.PrimitiveElement.PE_PanelLineEdit, option, painter, widget
        )

MenuDrawer

Drawer for QMenu using native QPainter calls (no QSS).

Paints the menu panel/border (PE_PanelMenu/PE_FrameMenu) and each item row (CE_MenuItem).

Source code in client/ayon_core/ui/drawers/menu.py
 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
class MenuDrawer:
    """Drawer for QMenu using native QPainter calls (no QSS).

    Paints the menu panel/border (PE_PanelMenu/PE_FrameMenu) and each
    item row (CE_MenuItem).
    """

    _WIDGET_CLS = "QMenu"
    # Horizontal and vertical padding of the box around shortcut text
    _SHORTCUT_PADDING = (5, 2)

    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def base_class(self) -> dict:
        return {"QMenu": QMenu}

    # ------------------------------------------------------------------
    # Registration
    # ------------------------------------------------------------------

    def register_drawers(self) -> dict:
        return {
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_PanelMenu,
                "QMenu",
            ): self.draw_panel,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_FrameMenu,
                "QMenu",
            ): self.draw_frame,
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_MenuItem,
                "QMenu",
            ): self.draw_menu_item,
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_MenuEmptyArea,
                "QMenu",
            ): do_nothing,
        }

    def register_sizers(self) -> dict:
        return {
            enum_to_str(
                QStyle.ContentsType,
                QStyle.ContentsType.CT_MenuItem,
                "QMenu",
            ): self.menu_item_size,
        }

    def register_metrics(self) -> dict:
        pm = QStyle.PixelMetric
        metrics_map = {
            pm.PM_MenuPanelWidth: self.get_metric,
            pm.PM_MenuHMargin: self.get_metric,
            pm.PM_MenuVMargin: self.get_metric,
            pm.PM_SmallIconSize: self.get_metric,
            pm.PM_MenuButtonIndicator: self.get_metric,
        }
        return {enum_to_str(pm, k, "QMenu"): v for k, v in metrics_map.items()}

    # ------------------------------------------------------------------
    # Metrics
    # ------------------------------------------------------------------

    def _base_style(self, widget: QWidget | None = None):
        """Return the base style dict, context-bound to *widget*.

        This is used for general operations like metrics calculation and
        panel/frame painting, where the state/variant-specific styles are
        not relevant.
        """
        variant = (
            widget.property("variant")
            if widget is not None
            else None
        ) or "default"
        style = self.model.get_style(self._WIDGET_CLS, variant, "base")
        style.set_context(widget)
        return style

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ) -> int:
        pm = QStyle.PixelMetric
        style = self._base_style(widget)
        if metric == pm.PM_MenuPanelWidth:
            return int(style.get("border-width", 1))
        if metric in (pm.PM_MenuHMargin, pm.PM_MenuVMargin):
            pp = style.get("panel-padding", [4, 4])
            if isinstance(pp, (list, tuple)):
                return int(pp[0] if metric == pm.PM_MenuHMargin else pp[1])
            return int(pp)
        if metric == pm.PM_SmallIconSize:
            return int(style.get("icon-size", 16))
        if metric == pm.PM_MenuButtonIndicator:
            return int(style.get("icon-size", 16))
        return 0

    # ------------------------------------------------------------------
    # Sizing and Layout Helper
    # ------------------------------------------------------------------

    def _compute_layout(
        self,
        option: QStyleOptionMenuItem,
        style: dict[str, Any],
        contents_size: QSize | None = None,
    ) -> MenuItemLayout:
        """Compute the metrics, dimensions and layouts for a menu item.

        Args:
            option: The style option for the menu item.
            style: The resolved style dict.
            contents_size: Optional contents size passed from size query.

        Returns:
            The computed layout information for the menu item.
        """
        ip = style.get("item-padding", [6, 6])
        if isinstance(ip, (list, tuple)):
            pad_h, pad_v = int(ip[0]), int(ip[1])
        else:
            pad_h = pad_v = int(ip)

        icon_size = int(style.get("icon-size", 16))
        item_spacing = int(style.get("item-spacing", 4))

        fm = option.fontMetrics
        text_h = QFontMetrics(self.model.base_font).height()
        if text_h <= 0:
            text_h = (
                contents_size.height()
                if contents_size
                else option.rect.height()
            )

        min_h = int(style.get("min-item-height", 0))
        row_h = max(text_h + pad_v * 2, icon_size + pad_v * 2, min_h)

        text = option.text or ""
        label, _, shortcut = text.partition("\t")
        if doc := _rich_text_document(label, option.font):
            text_w = math.ceil(doc.idealWidth())
        elif fm:
            text_w = fm.horizontalAdvance(label)
        else:
            text_w = contents_size.width() if contents_size else 0

        sc_w = getattr(
            option,
            "reservedShortcutWidth",
            getattr(option, "tabWidth", 0),
        )
        if shortcut and sc_w == 0 and fm:
            sc_w = fm.horizontalAdvance(shortcut)
        if sc_w:
            # Shortcut is drawn with smaller font inside a padded box
            scale = float(style.get("shortcut-font-scale", 0.85))
            sc_w = int(sc_w * scale) + self._SHORTCUT_PADDING[0] * 2

        icon_gutter = icon_size + item_spacing
        is_submenu = (
            option.menuItemType == QStyleOptionMenuItem.MenuItemType.SubMenu
        )
        arrow_w = icon_size if is_submenu else 0
        # The arrow glyph only covers the middle of its icon, the blank
        # part of the icon around it already acts as padding. Use less
        # padding next to it so the arrow is not left far from the edge.
        arrow_pad = pad_h // 2

        total_w = (
            icon_gutter
            + pad_h
            + text_w
            + (pad_h + sc_w if sc_w else 0)
            + (pad_h + arrow_w + arrow_pad if arrow_w else pad_h)
        )

        return MenuItemLayout(
            pad_h=pad_h,
            pad_v=pad_v,
            icon_size=icon_size,
            item_spacing=item_spacing,
            icon_gutter=icon_gutter,
            label_text=label,
            shortcut_text=shortcut,
            text_w=text_w,
            text_h=text_h,
            sc_w=sc_w,
            arrow_w=arrow_w,
            arrow_pad=arrow_pad,
            row_h=row_h,
            total_w=total_w,
        )

    def menu_item_size(
        self,
        contents_type: QStyle.ContentsType,
        option: QStyleOption | None,
        contents_size: QSize,
        widget: QWidget | None = None,
    ) -> QSize:
        """Compute the bounding size of a single menu item row."""
        if not isinstance(option, QStyleOptionMenuItem):
            return QSize(contents_size.width(), contents_size.height())

        style = self._base_style(widget)

        # Separator: early exit
        sep_type = QStyleOptionMenuItem.MenuItemType.Separator
        if option.menuItemType == sep_type:
            sep_h = int(style.get("separator-height", 1))
            return QSize(contents_size.width(), sep_h)

        layout = self._compute_layout(option, style, contents_size)
        return QSize(
            layout.total_w,
            layout.row_h,
        )

    # ------------------------------------------------------------------
    # Primitive painting: panel & frame
    # ------------------------------------------------------------------

    def draw_panel(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Fill the menu background with the panel colour."""
        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        style = self._base_style(widget)
        radius = int(style.get("border-radius", 6))
        painter.setBrush(QBrush(QColor(style["background-color"])))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(option.rect, radius, radius)
        painter.restore()

    def draw_frame(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Stroke the menu border."""
        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        style = self._base_style(widget)
        radius = int(style.get("border-radius", 6))
        bw = int(style.get("border-width", 1))
        pen = QPen(QColor(style["border-color"]))
        pen.setWidth(bw)
        painter.setPen(pen)
        painter.setBrush(Qt.BrushStyle.NoBrush)
        # Inset by half the pen width so the stroke is fully inside the rect.
        inset = bw / 2.0
        inset_rect = QRectF(option.rect).adjusted(inset, inset, -inset, -inset)
        painter.drawRoundedRect(inset_rect, radius, radius)
        painter.restore()

    # ------------------------------------------------------------------
    # Control painting: individual item rows
    # ------------------------------------------------------------------

    def draw_menu_item(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Paint a single QMenu row (normal, separator, submenu)."""
        if not isinstance(option, QStyleOptionMenuItem):
            return

        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)

        # Handle separators and return
        sep_type = QStyleOptionMenuItem.MenuItemType.Separator
        if option.menuItemType == sep_type:
            self._draw_separator(option, painter, widget)
            painter.restore()
            return

        # Resolve state and fetch styles
        is_enabled = bool(option.state & QStyle.StateFlag.State_Enabled)
        is_selected = bool(option.state & QStyle.StateFlag.State_Selected)
        state = (
            "disabled"
            if not is_enabled
            else "hover"
            if is_selected and is_enabled
            else "base"
        )

        # Resolve variant from action property, if available
        # NOTE: This is a bit of a hack. I could have created a QAction section
        # in ayon_style.json and fetched the variant from there.
        action = None
        if isinstance(widget, QMenu):
            action = widget.actionAt(option.rect.center())
        variant = (
            (action.property("variant") if action else None)
            or (widget.property("variant") if widget else None)
            or "default"
        )

        style = self.model.get_style(
            self._WIDGET_CLS, variant=variant, state=state
        )
        style.set_context(widget)

        layout = self._compute_layout(option, style)
        item_radius = int(style.get("item-radius", 4))
        rect = option.rect

        # --- Selection background ---
        bg = QColor(style.get("background-color", "#424a57"))
        painter.setBrush(QBrush(bg))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(rect, item_radius, item_radius)

        opacity = float(style.get("opacity", 1.0))
        painter.setOpacity(opacity)

        # --- Left gutter (icon or check mark) ---
        x = rect.left() + layout.pad_h
        cy = rect.center().y()
        # Icons are drawn slightly towards the edge, away from the label
        icon_x = x - 2

        check_type = option.checkType
        not_checkable = QStyleOptionMenuItem.CheckType.NotCheckable
        if check_type != not_checkable:
            check_color = QColor(style.get("color", "#f4f5f5"))
            check_style = (
                action.property("check-style") if action else None
            )
            if option.checked or check_style != "checkmark":
                if check_style == "checkmark":
                    icon_name = "check"
                elif option.checked:
                    icon_name = "check_box"
                else:
                    icon_name = "check_box_outline_blank"
                check_icon = get_icon(
                    icon_name,
                    color=check_color,
                    fill=False,
                )
                check_rect = QRect(
                    icon_x,
                    cy - layout.icon_size // 2,
                    layout.icon_size,
                    layout.icon_size,
                )
                check_icon.paint(painter, check_rect)
        elif not option.icon.isNull():
            icon_rect = QRect(
                icon_x,
                cy - layout.icon_size // 2,
                layout.icon_size,
                layout.icon_size,
            )
            mode = QIcon.Mode.Disabled if not is_enabled else QIcon.Mode.Normal
            option.icon.paint(
                painter, icon_rect, Qt.AlignmentFlag.AlignCenter, mode
            )

        x += layout.icon_gutter

        # --- Text (label + shortcut) ---
        text_color = QColor(style.get("color", "#f4f5f5"))
        painter.setPen(QPen(text_color))

        right_margin = (
            layout.pad_h + layout.arrow_w + layout.arrow_pad
            if layout.arrow_w
            else layout.pad_h
        )
        # 'rect.right()' is the last pixel inside the rect, one short of
        # its right edge - without the '+ 1' the label is a pixel narrower
        # than the width measured for it and loses its last character.
        label_rect = QRect(
            x,
            rect.top(),
            rect.right()
            + 1
            - x
            - right_margin
            - (layout.sc_w + layout.pad_h if layout.sc_w else 0),
            rect.height(),
        )
        if doc := _rich_text_document(layout.label_text, painter.font()):
            self._draw_rich_text(painter, doc, label_rect, text_color)
        else:
            # Not clipped: with fractional font metrics (display scaling)
            # the text can still be a pixel wider than measured, the
            # padding next to it has room for that.
            painter.drawText(
                label_rect,
                Qt.AlignmentFlag.AlignVCenter
                | Qt.AlignmentFlag.AlignLeft
                | Qt.TextFlag.TextDontClip,
                layout.label_text,
            )

        if layout.shortcut_text:
            sc_bg_color = QColor(
                style.get(
                    "shortcut-background-color",
                    style.get("background-color", "#2b3036"),
                )
            )
            # Shortcut is a hint, draw it smaller than the label inside
            # a rounded box aligned to the right side of the row.
            sc_font = QFont(painter.font())
            scale = float(style.get("shortcut-font-scale", 0.85))
            if sc_font.pixelSize() > 0:
                sc_font.setPixelSize(
                    max(1, round(sc_font.pixelSize() * scale))
                )
            else:
                sc_font.setPointSizeF(sc_font.pointSizeF() * scale)
            painter.setFont(sc_font)

            sc_fm = QFontMetrics(sc_font)
            sc_pad_h, sc_pad_v = self._SHORTCUT_PADDING
            sc_rect = QRect(
                0,
                0,
                sc_fm.horizontalAdvance(layout.shortcut_text)
                + sc_pad_h * 2,
                sc_fm.height() + sc_pad_v * 2,
            )
            sc_rect.moveCenter(rect.center())
            sc_rect.moveRight(rect.right() - right_margin)
            painter.setBrush(QBrush(sc_bg_color))
            painter.setPen(Qt.PenStyle.NoPen)
            painter.drawRoundedRect(sc_rect, 4, 4)

            sc_color = QColor(
                style.get(
                    "shortcut-color",
                    style.get("color", "#8b9198"),
                )
            )
            sc_color.setAlphaF(style.get("shortcut-opacity", 0.6))
            painter.setPen(QPen(sc_color))
            painter.drawText(
                sc_rect,
                Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter,
                layout.shortcut_text,
            )

        # --- Submenu arrow ---
        if layout.arrow_w > 0:
            arrow_color = QColor(style.get("color", "#f4f5f5"))
            arrow_icon = get_icon("chevron_right", color=arrow_color)
            arrow_rect = QRect(
                rect.right() - layout.arrow_pad - layout.arrow_w,
                cy - layout.icon_size // 2,
                layout.icon_size,
                layout.icon_size,
            )
            arrow_icon.paint(painter, arrow_rect)

        painter.restore()

    @staticmethod
    def _draw_rich_text(
        painter: QPainter,
        doc: QTextDocument,
        rect: QRect,
        color: QColor,
    ) -> None:
        """Draw a rich text label vertically centered in *rect*."""
        height = doc.size().height()

        painter.save()
        painter.translate(
            rect.left(),
            rect.top() + (rect.height() - height) / 2.0,
        )

        # paint
        context = QAbstractTextDocumentLayout.PaintContext()
        context.palette.setColor(QPalette.ColorRole.Text, color)
        doc.documentLayout().draw(painter, context)

        painter.restore()

    def _draw_separator(
        self,
        option: QStyleOptionMenuItem,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Draw a thin horizontal separator line."""
        style = self._base_style(widget)
        color = QColor(
            style.get("separator-color", style.get("border-color", "#41474d"))
        )
        sep_h = int(style.get("separator-height", 1))

        cy = option.rect.center().y()
        y = cy - sep_h // 2
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(QBrush(color))
        painter.drawRect(
            option.rect.left(),
            y,
            option.rect.width(),
            sep_h,
        )

draw_frame(option, painter, widget=None)

Stroke the menu border.

Source code in client/ayon_core/ui/drawers/menu.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def draw_frame(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Stroke the menu border."""
    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
    style = self._base_style(widget)
    radius = int(style.get("border-radius", 6))
    bw = int(style.get("border-width", 1))
    pen = QPen(QColor(style["border-color"]))
    pen.setWidth(bw)
    painter.setPen(pen)
    painter.setBrush(Qt.BrushStyle.NoBrush)
    # Inset by half the pen width so the stroke is fully inside the rect.
    inset = bw / 2.0
    inset_rect = QRectF(option.rect).adjusted(inset, inset, -inset, -inset)
    painter.drawRoundedRect(inset_rect, radius, radius)
    painter.restore()

draw_menu_item(option, painter, widget=None)

Paint a single QMenu row (normal, separator, submenu).

Source code in client/ayon_core/ui/drawers/menu.py
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
def draw_menu_item(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Paint a single QMenu row (normal, separator, submenu)."""
    if not isinstance(option, QStyleOptionMenuItem):
        return

    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)

    # Handle separators and return
    sep_type = QStyleOptionMenuItem.MenuItemType.Separator
    if option.menuItemType == sep_type:
        self._draw_separator(option, painter, widget)
        painter.restore()
        return

    # Resolve state and fetch styles
    is_enabled = bool(option.state & QStyle.StateFlag.State_Enabled)
    is_selected = bool(option.state & QStyle.StateFlag.State_Selected)
    state = (
        "disabled"
        if not is_enabled
        else "hover"
        if is_selected and is_enabled
        else "base"
    )

    # Resolve variant from action property, if available
    # NOTE: This is a bit of a hack. I could have created a QAction section
    # in ayon_style.json and fetched the variant from there.
    action = None
    if isinstance(widget, QMenu):
        action = widget.actionAt(option.rect.center())
    variant = (
        (action.property("variant") if action else None)
        or (widget.property("variant") if widget else None)
        or "default"
    )

    style = self.model.get_style(
        self._WIDGET_CLS, variant=variant, state=state
    )
    style.set_context(widget)

    layout = self._compute_layout(option, style)
    item_radius = int(style.get("item-radius", 4))
    rect = option.rect

    # --- Selection background ---
    bg = QColor(style.get("background-color", "#424a57"))
    painter.setBrush(QBrush(bg))
    painter.setPen(Qt.PenStyle.NoPen)
    painter.drawRoundedRect(rect, item_radius, item_radius)

    opacity = float(style.get("opacity", 1.0))
    painter.setOpacity(opacity)

    # --- Left gutter (icon or check mark) ---
    x = rect.left() + layout.pad_h
    cy = rect.center().y()
    # Icons are drawn slightly towards the edge, away from the label
    icon_x = x - 2

    check_type = option.checkType
    not_checkable = QStyleOptionMenuItem.CheckType.NotCheckable
    if check_type != not_checkable:
        check_color = QColor(style.get("color", "#f4f5f5"))
        check_style = (
            action.property("check-style") if action else None
        )
        if option.checked or check_style != "checkmark":
            if check_style == "checkmark":
                icon_name = "check"
            elif option.checked:
                icon_name = "check_box"
            else:
                icon_name = "check_box_outline_blank"
            check_icon = get_icon(
                icon_name,
                color=check_color,
                fill=False,
            )
            check_rect = QRect(
                icon_x,
                cy - layout.icon_size // 2,
                layout.icon_size,
                layout.icon_size,
            )
            check_icon.paint(painter, check_rect)
    elif not option.icon.isNull():
        icon_rect = QRect(
            icon_x,
            cy - layout.icon_size // 2,
            layout.icon_size,
            layout.icon_size,
        )
        mode = QIcon.Mode.Disabled if not is_enabled else QIcon.Mode.Normal
        option.icon.paint(
            painter, icon_rect, Qt.AlignmentFlag.AlignCenter, mode
        )

    x += layout.icon_gutter

    # --- Text (label + shortcut) ---
    text_color = QColor(style.get("color", "#f4f5f5"))
    painter.setPen(QPen(text_color))

    right_margin = (
        layout.pad_h + layout.arrow_w + layout.arrow_pad
        if layout.arrow_w
        else layout.pad_h
    )
    # 'rect.right()' is the last pixel inside the rect, one short of
    # its right edge - without the '+ 1' the label is a pixel narrower
    # than the width measured for it and loses its last character.
    label_rect = QRect(
        x,
        rect.top(),
        rect.right()
        + 1
        - x
        - right_margin
        - (layout.sc_w + layout.pad_h if layout.sc_w else 0),
        rect.height(),
    )
    if doc := _rich_text_document(layout.label_text, painter.font()):
        self._draw_rich_text(painter, doc, label_rect, text_color)
    else:
        # Not clipped: with fractional font metrics (display scaling)
        # the text can still be a pixel wider than measured, the
        # padding next to it has room for that.
        painter.drawText(
            label_rect,
            Qt.AlignmentFlag.AlignVCenter
            | Qt.AlignmentFlag.AlignLeft
            | Qt.TextFlag.TextDontClip,
            layout.label_text,
        )

    if layout.shortcut_text:
        sc_bg_color = QColor(
            style.get(
                "shortcut-background-color",
                style.get("background-color", "#2b3036"),
            )
        )
        # Shortcut is a hint, draw it smaller than the label inside
        # a rounded box aligned to the right side of the row.
        sc_font = QFont(painter.font())
        scale = float(style.get("shortcut-font-scale", 0.85))
        if sc_font.pixelSize() > 0:
            sc_font.setPixelSize(
                max(1, round(sc_font.pixelSize() * scale))
            )
        else:
            sc_font.setPointSizeF(sc_font.pointSizeF() * scale)
        painter.setFont(sc_font)

        sc_fm = QFontMetrics(sc_font)
        sc_pad_h, sc_pad_v = self._SHORTCUT_PADDING
        sc_rect = QRect(
            0,
            0,
            sc_fm.horizontalAdvance(layout.shortcut_text)
            + sc_pad_h * 2,
            sc_fm.height() + sc_pad_v * 2,
        )
        sc_rect.moveCenter(rect.center())
        sc_rect.moveRight(rect.right() - right_margin)
        painter.setBrush(QBrush(sc_bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(sc_rect, 4, 4)

        sc_color = QColor(
            style.get(
                "shortcut-color",
                style.get("color", "#8b9198"),
            )
        )
        sc_color.setAlphaF(style.get("shortcut-opacity", 0.6))
        painter.setPen(QPen(sc_color))
        painter.drawText(
            sc_rect,
            Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter,
            layout.shortcut_text,
        )

    # --- Submenu arrow ---
    if layout.arrow_w > 0:
        arrow_color = QColor(style.get("color", "#f4f5f5"))
        arrow_icon = get_icon("chevron_right", color=arrow_color)
        arrow_rect = QRect(
            rect.right() - layout.arrow_pad - layout.arrow_w,
            cy - layout.icon_size // 2,
            layout.icon_size,
            layout.icon_size,
        )
        arrow_icon.paint(painter, arrow_rect)

    painter.restore()

draw_panel(option, painter, widget=None)

Fill the menu background with the panel colour.

Source code in client/ayon_core/ui/drawers/menu.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def draw_panel(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Fill the menu background with the panel colour."""
    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
    style = self._base_style(widget)
    radius = int(style.get("border-radius", 6))
    painter.setBrush(QBrush(QColor(style["background-color"])))
    painter.setPen(Qt.PenStyle.NoPen)
    painter.drawRoundedRect(option.rect, radius, radius)
    painter.restore()

menu_item_size(contents_type, option, contents_size, widget=None)

Compute the bounding size of a single menu item row.

Source code in client/ayon_core/ui/drawers/menu.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def menu_item_size(
    self,
    contents_type: QStyle.ContentsType,
    option: QStyleOption | None,
    contents_size: QSize,
    widget: QWidget | None = None,
) -> QSize:
    """Compute the bounding size of a single menu item row."""
    if not isinstance(option, QStyleOptionMenuItem):
        return QSize(contents_size.width(), contents_size.height())

    style = self._base_style(widget)

    # Separator: early exit
    sep_type = QStyleOptionMenuItem.MenuItemType.Separator
    if option.menuItemType == sep_type:
        sep_h = int(style.get("separator-height", 1))
        return QSize(contents_size.width(), sep_h)

    layout = self._compute_layout(option, style, contents_size)
    return QSize(
        layout.total_w,
        layout.row_h,
    )

ScrollBarDrawer

Source code in client/ayon_core/ui/drawers/scrollbar.py
 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
class ScrollBarDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model
        self._style = self.model.get_style("QScrollBar")

    @property
    def base_class(self):
        return {"QScrollBar": QtWidgets.QScrollBar}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_ScrollBar,
                "QScrollBar",
            ): self.draw_scrollbar,
        }

    def register_sizers(self):
        return {
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_ScrollBar,
                "QScrollBar",
            ): self.get_size,
        }

    def register_metrics(self):
        return {
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_ScrollBarExtent,
                "QScrollBar",
            ): self.get_metric,
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_ScrollBarSliderMin,
                "QScrollBar",
            ): self.get_metric,
        }

    def get_size(
        self,
        cc: QStyle.ComplexControl,
        opt: QStyleOptionComplex,
        sc: QStyle.SubControl,
        w: QWidget | None = None,
    ) -> QRect | None:
        """Sub-control rects for a scrollbar without arrow buttons.

        Mirrors QCommonStyle's layout but with the groove spanning the
        whole widget. Painting and all mouse interaction (hit testing,
        dragging, page stepping) query these rects, so what is drawn is
        exactly what responds to the mouse.
        """
        opt = self._slider_option(opt, w)
        SC = QStyle.SubControl
        # No arrow buttons: report them as empty so they never get painted
        # nor hit by 'hitTestComplexControl'.
        if sc not in (
            SC.SC_ScrollBarGroove,
            SC.SC_ScrollBarSlider,
            SC.SC_ScrollBarSubPage,
            SC.SC_ScrollBarAddPage,
        ):
            return QRect()

        rect = opt.rect
        horizontal = opt.orientation == Qt.Orientation.Horizontal
        max_len = rect.width() if horizontal else rect.height()

        slider_len = max_len
        if opt.maximum != opt.minimum:
            value_range = opt.maximum - opt.minimum
            slider_len = int(
                opt.pageStep * max_len / (value_range + opt.pageStep)
            )
            slider_min = self.style_inst.pixelMetric(
                QStyle.PixelMetric.PM_ScrollBarSliderMin, opt, w
            )
            slider_len = min(max(slider_len, slider_min), max_len)

        slider_start = QStyle.sliderPositionFromValue(
            opt.minimum,
            opt.maximum,
            opt.sliderPosition,
            max_len - slider_len,
            opt.upsideDown,
        )

        if sc == SC.SC_ScrollBarGroove:
            start, length = 0, max_len
        elif sc == SC.SC_ScrollBarSlider:
            start, length = slider_start, slider_len
        elif sc == SC.SC_ScrollBarSubPage:
            start, length = 0, slider_start
        else:  # SC_ScrollBarAddPage
            start = slider_start + slider_len
            length = max_len - start

        if horizontal:
            ret = QRect(start, 0, length, rect.height())
        else:
            ret = QRect(0, start, rect.width(), length)
        return QStyle.visualRect(opt.direction, rect, ret)

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ) -> int:
        self._style.set_context(widget)
        if metric == QStyle.PixelMetric.PM_ScrollBarExtent:
            # Width of a vertical scroll bar and the height of a horizontal
            # scroll bar.
            return int(self._style["width"])
        elif metric == QStyle.PixelMetric.PM_ScrollBarSliderMin:
            # The minimum height of a vertical scroll bar's slider and the
            # minimum width of a horizontal scroll bar's slider.
            return int(self._style["min-length"])
        return 0

    @staticmethod
    def _slider_option(
        opt: QStyleOption, w: QWidget | None
    ) -> QStyleOptionSlider:
        """Return ``opt`` as a QStyleOptionSlider.

        PySide2 does not downcast style options that Qt passes from C++ into
        Python overrides (e.g. from 'hitTestComplexControl'), so they arrive
        as QStyleOptionComplex without the slider fields. Rebuild those from
        the scrollbar widget in that case.
        """
        if isinstance(opt, QStyleOptionSlider):
            return opt
        if not isinstance(w, QtWidgets.QScrollBar):
            raise ValueError(f"Unexpected option type: {type(opt)}")
        slider_opt = QStyleOptionSlider()
        slider_opt.initFrom(w)
        slider_opt.rect = opt.rect
        slider_opt.state = opt.state
        slider_opt.direction = opt.direction
        if isinstance(opt, QStyleOptionComplex):
            slider_opt.subControls = opt.subControls
            slider_opt.activeSubControls = opt.activeSubControls
        slider_opt.orientation = w.orientation()
        slider_opt.minimum = w.minimum()
        slider_opt.maximum = w.maximum()
        slider_opt.sliderPosition = w.sliderPosition()
        slider_opt.sliderValue = w.value()
        slider_opt.singleStep = w.singleStep()
        slider_opt.pageStep = w.pageStep()
        slider_opt.upsideDown = w.invertedAppearance()
        return slider_opt

    def draw_scrollbar(
        self,
        option: QStyleOptionComplex,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Draw the scrollbar background and slider."""
        option = self._slider_option(option, widget)
        style = self.model.get_style("QScrollBar")
        style.set_context(widget)
        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        painter.setPen(Qt.PenStyle.NoPen)

        painter.setBrush(QBrush(QColor(style["background-color"])))
        painter.drawRect(option.rect)

        if not option.subControls & QStyle.SubControl.SC_ScrollBarSlider:
            painter.restore()
            return

        rect = self.get_size(
            QStyle.ComplexControl.CC_ScrollBar,
            option,
            QStyle.SubControl.SC_ScrollBarSlider,
            widget,
        )
        size = style["slider-width"]
        center = rect.center()
        if option.orientation == Qt.Orientation.Vertical:
            rect.setWidth(size)
        else:
            rect.setHeight(size)
        rect.moveCenter(center)

        radius = min(
            style.get("border-radius"), rect.width() / 2, rect.height() / 2
        )
        if option.state & QStyle.StateFlag.State_Sunken:
            slider_color = QColor(style.get("slider-active-color"))
        elif option.activeSubControls & QStyle.SubControl.SC_ScrollBarSlider:
            slider_color = QColor(style.get("slider-hover-color"))
        else:
            slider_color = QColor(style.get("slider-color"))
        painter.setBrush(QBrush(slider_color))
        painter.drawRoundedRect(rect, radius, radius)

        painter.restore()

draw_scrollbar(option, painter, widget=None)

Draw the scrollbar background and slider.

Source code in client/ayon_core/ui/drawers/scrollbar.py
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
def draw_scrollbar(
    self,
    option: QStyleOptionComplex,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Draw the scrollbar background and slider."""
    option = self._slider_option(option, widget)
    style = self.model.get_style("QScrollBar")
    style.set_context(widget)
    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)
    painter.setPen(Qt.PenStyle.NoPen)

    painter.setBrush(QBrush(QColor(style["background-color"])))
    painter.drawRect(option.rect)

    if not option.subControls & QStyle.SubControl.SC_ScrollBarSlider:
        painter.restore()
        return

    rect = self.get_size(
        QStyle.ComplexControl.CC_ScrollBar,
        option,
        QStyle.SubControl.SC_ScrollBarSlider,
        widget,
    )
    size = style["slider-width"]
    center = rect.center()
    if option.orientation == Qt.Orientation.Vertical:
        rect.setWidth(size)
    else:
        rect.setHeight(size)
    rect.moveCenter(center)

    radius = min(
        style.get("border-radius"), rect.width() / 2, rect.height() / 2
    )
    if option.state & QStyle.StateFlag.State_Sunken:
        slider_color = QColor(style.get("slider-active-color"))
    elif option.activeSubControls & QStyle.SubControl.SC_ScrollBarSlider:
        slider_color = QColor(style.get("slider-hover-color"))
    else:
        slider_color = QColor(style.get("slider-color"))
    painter.setBrush(QBrush(slider_color))
    painter.drawRoundedRect(rect, radius, radius)

    painter.restore()

get_size(cc, opt, sc, w=None)

Sub-control rects for a scrollbar without arrow buttons.

Mirrors QCommonStyle's layout but with the groove spanning the whole widget. Painting and all mouse interaction (hit testing, dragging, page stepping) query these rects, so what is drawn is exactly what responds to the mouse.

Source code in client/ayon_core/ui/drawers/scrollbar.py
 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
def get_size(
    self,
    cc: QStyle.ComplexControl,
    opt: QStyleOptionComplex,
    sc: QStyle.SubControl,
    w: QWidget | None = None,
) -> QRect | None:
    """Sub-control rects for a scrollbar without arrow buttons.

    Mirrors QCommonStyle's layout but with the groove spanning the
    whole widget. Painting and all mouse interaction (hit testing,
    dragging, page stepping) query these rects, so what is drawn is
    exactly what responds to the mouse.
    """
    opt = self._slider_option(opt, w)
    SC = QStyle.SubControl
    # No arrow buttons: report them as empty so they never get painted
    # nor hit by 'hitTestComplexControl'.
    if sc not in (
        SC.SC_ScrollBarGroove,
        SC.SC_ScrollBarSlider,
        SC.SC_ScrollBarSubPage,
        SC.SC_ScrollBarAddPage,
    ):
        return QRect()

    rect = opt.rect
    horizontal = opt.orientation == Qt.Orientation.Horizontal
    max_len = rect.width() if horizontal else rect.height()

    slider_len = max_len
    if opt.maximum != opt.minimum:
        value_range = opt.maximum - opt.minimum
        slider_len = int(
            opt.pageStep * max_len / (value_range + opt.pageStep)
        )
        slider_min = self.style_inst.pixelMetric(
            QStyle.PixelMetric.PM_ScrollBarSliderMin, opt, w
        )
        slider_len = min(max(slider_len, slider_min), max_len)

    slider_start = QStyle.sliderPositionFromValue(
        opt.minimum,
        opt.maximum,
        opt.sliderPosition,
        max_len - slider_len,
        opt.upsideDown,
    )

    if sc == SC.SC_ScrollBarGroove:
        start, length = 0, max_len
    elif sc == SC.SC_ScrollBarSlider:
        start, length = slider_start, slider_len
    elif sc == SC.SC_ScrollBarSubPage:
        start, length = 0, slider_start
    else:  # SC_ScrollBarAddPage
        start = slider_start + slider_len
        length = max_len - start

    if horizontal:
        ret = QRect(start, 0, length, rect.height())
    else:
        ret = QRect(0, start, rect.width(), length)
    return QStyle.visualRect(opt.direction, rect, ret)

SpinBoxDrawer

Source code in client/ayon_core/ui/drawers/spinbox.py
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
class SpinBoxDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QSpinBox": QSpinBox}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_SpinBox,
                "QSpinBox",
            ): self.draw_spinbox,
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_SpinBox,
                "QSpinBox",
            ): self.draw_spinbox,
        }

    def register_sizers(self):
        return {
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_SpinBox,
                "QSpinBox",
            ): self.sub_control_rect,
            enum_to_str(
                QStyle.ComplexControl,
                QStyle.ComplexControl.CC_SpinBox,
                "QSpinBox",
            ): self.sub_control_rect,
        }

    def sub_control_rect(
        self,
        cc: QStyle.ComplexControl,
        opt: QStyleOptionSpinBox,
        sc: QStyle.SubControl,
        w: QWidget | None = None,
    ):
        output = self._super.subControlRect(
            cc, opt, sc, w
        )
        if sc in (
            QStyle.SubControl.SC_SpinBoxUp,
            QStyle.SubControl.SC_SpinBoxDown,
        ):
            output.setLeft(output.right() - (output.height() + 1))
        return output

    def draw_spinbox(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None,
    ) -> None:
        from ayon_core.ui.components import AYSpinBox

        if isinstance(widget, AYSpinBox):
            return

        self._super.drawComplexControl(
            QStyle.ComplexControl.CC_SpinBox, option, painter, widget
        )

TableHeaderDrawer

AYONStyle drawer for QHeaderView used by AYTableView.

Handles painting of header sections and labels using colours from the AYTableView style data in ayon_style.json.

Source code in client/ayon_core/ui/drawers/table_header.py
 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
class TableHeaderDrawer:
    """AYONStyle drawer for QHeaderView used by AYTableView.

    Handles painting of header sections and labels using colours
    from the AYTableView style data in ayon_style.json.
    """

    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model
        self._icon_cache: dict[str, QIcon] = {}

    @property
    def base_class(self):
        return {"QHeaderView": QtWidgets.QHeaderView}

    def register_drawers(self) -> dict:
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_Header,
                "QHeaderView",
            ): [
                partial(
                    self.style_inst.drawControl,
                    QStyle.ControlElement.CE_HeaderSection,
                ),
                partial(
                    self.style_inst.drawControl,
                    QStyle.ControlElement.CE_HeaderLabel,
                ),
            ],
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_HeaderSection,
                "QHeaderView",
            ): self.draw_header_section,
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_HeaderLabel,
                "QHeaderView",
            ): self.draw_header_label,
        }

    def register_metrics(self) -> dict:
        """Register pixel metrics for QHeaderView."""
        return {
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_HeaderMargin,
                "QHeaderView",
            ): self.get_metric,
        }

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ) -> int:
        """Return header margin from style data."""
        if metric == QStyle.PixelMetric.PM_HeaderMargin:
            return 4
        return 0

    def _get_table_style(self, widget: QWidget | None) -> dict:
        """Resolve the AYTableView style for the header's parent table."""
        variant = "default"
        if widget is not None:
            # QHeaderView's parent is the QTreeView/AYTableView
            table = widget.parent()
            if table is not None:
                variant = getattr(table, "_variant_str", "default")
        return self.model.get_style("AYTableView", variant)

    def draw_header_section(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Draw the header section background and bottom border."""
        style = self._get_table_style(widget)

        painter.save()
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)

        # Background
        bg_color = QColor(style.get("header-background-color", "#272d35"))
        painter.setBrush(QBrush(bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRect(option.rect)

        # Bottom border
        border_color = QColor(style.get("header-border-color", "#41474d"))
        pen = QPen(border_color)
        pen.setWidth(1)
        painter.setPen(pen)
        bottom = option.rect.bottom()
        painter.drawLine(
            option.rect.left(),
            bottom,
            option.rect.right(),
            bottom,
        )

        painter.restore()

    def draw_header_label(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Draw the header label text and sort indicator."""
        style = self._get_table_style(widget)
        padding = style.get("header-padding", [4, 8])

        painter.save()

        # Text
        text_color = QColor(style.get("header-color", "#c1c7ce"))
        painter.setPen(text_color)

        font = painter.font()
        font.setWeight(QFont.Weight.DemiBold)
        painter.setFont(font)

        text_rect = option.rect.adjusted(
            padding[1], padding[0], -padding[1], -padding[0]
        )

        text = ""
        if hasattr(option, "text"):
            text = option.text or ""

        # Check for sort indicator
        sort_indicator = getattr(option, "sortIndicator", None)
        indicator_space = 0
        if sort_indicator and sort_indicator != 0:
            indicator_space = 16

        if text:
            draw_rect = QRect(text_rect)
            if indicator_space:
                draw_rect.setRight(draw_rect.right() - indicator_space)
            painter.drawText(
                draw_rect,
                Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
                text,
            )

        # Sort indicator arrow
        if sort_indicator and sort_indicator != 0:
            indicator_color = QColor(
                style.get(
                    "header-sort-indicator-color",
                    "#8fceff",
                )
            )
            # sortIndicator: 1 = Down, 2 = Up (in QStyleOptionHeader)
            icon_name = (
                "arrow_downward" if sort_indicator == 1 else "arrow_upward"
            )
            cache_key = f"{icon_name}-{indicator_color.name()}"
            if cache_key not in self._icon_cache:
                self._icon_cache[cache_key] = get_icon(
                    icon_name, color=indicator_color
                )
            icon = self._icon_cache[cache_key]
            icon_rect = QRect(
                text_rect.right() - 14,
                text_rect.center().y() - 7,
                14,
                14,
            )
            icon.paint(painter, icon_rect)

        painter.restore()

draw_header_label(option, painter, widget=None)

Draw the header label text and sort indicator.

Source code in client/ayon_core/ui/drawers/table_header.py
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
def draw_header_label(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Draw the header label text and sort indicator."""
    style = self._get_table_style(widget)
    padding = style.get("header-padding", [4, 8])

    painter.save()

    # Text
    text_color = QColor(style.get("header-color", "#c1c7ce"))
    painter.setPen(text_color)

    font = painter.font()
    font.setWeight(QFont.Weight.DemiBold)
    painter.setFont(font)

    text_rect = option.rect.adjusted(
        padding[1], padding[0], -padding[1], -padding[0]
    )

    text = ""
    if hasattr(option, "text"):
        text = option.text or ""

    # Check for sort indicator
    sort_indicator = getattr(option, "sortIndicator", None)
    indicator_space = 0
    if sort_indicator and sort_indicator != 0:
        indicator_space = 16

    if text:
        draw_rect = QRect(text_rect)
        if indicator_space:
            draw_rect.setRight(draw_rect.right() - indicator_space)
        painter.drawText(
            draw_rect,
            Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
            text,
        )

    # Sort indicator arrow
    if sort_indicator and sort_indicator != 0:
        indicator_color = QColor(
            style.get(
                "header-sort-indicator-color",
                "#8fceff",
            )
        )
        # sortIndicator: 1 = Down, 2 = Up (in QStyleOptionHeader)
        icon_name = (
            "arrow_downward" if sort_indicator == 1 else "arrow_upward"
        )
        cache_key = f"{icon_name}-{indicator_color.name()}"
        if cache_key not in self._icon_cache:
            self._icon_cache[cache_key] = get_icon(
                icon_name, color=indicator_color
            )
        icon = self._icon_cache[cache_key]
        icon_rect = QRect(
            text_rect.right() - 14,
            text_rect.center().y() - 7,
            14,
            14,
        )
        icon.paint(painter, icon_rect)

    painter.restore()

draw_header_section(option, painter, widget=None)

Draw the header section background and bottom border.

Source code in client/ayon_core/ui/drawers/table_header.py
 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
def draw_header_section(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Draw the header section background and bottom border."""
    style = self._get_table_style(widget)

    painter.save()
    painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)

    # Background
    bg_color = QColor(style.get("header-background-color", "#272d35"))
    painter.setBrush(QBrush(bg_color))
    painter.setPen(Qt.PenStyle.NoPen)
    painter.drawRect(option.rect)

    # Bottom border
    border_color = QColor(style.get("header-border-color", "#41474d"))
    pen = QPen(border_color)
    pen.setWidth(1)
    painter.setPen(pen)
    bottom = option.rect.bottom()
    painter.drawLine(
        option.rect.left(),
        bottom,
        option.rect.right(),
        bottom,
    )

    painter.restore()

get_metric(metric, opt=None, widget=None)

Return header margin from style data.

Source code in client/ayon_core/ui/drawers/table_header.py
73
74
75
76
77
78
79
80
81
82
def get_metric(
    self,
    metric: QStyle.PixelMetric,
    opt: QStyleOption | None = None,
    widget: QWidget | None = None,
) -> int:
    """Return header margin from style data."""
    if metric == QStyle.PixelMetric.PM_HeaderMargin:
        return 4
    return 0

register_metrics()

Register pixel metrics for QHeaderView.

Source code in client/ayon_core/ui/drawers/table_header.py
63
64
65
66
67
68
69
70
71
def register_metrics(self) -> dict:
    """Register pixel metrics for QHeaderView."""
    return {
        enum_to_str(
            QStyle.PixelMetric,
            QStyle.PixelMetric.PM_HeaderMargin,
            "QHeaderView",
        ): self.get_metric,
    }

TooltipDrawer

Source code in client/ayon_core/ui/drawers/tooltip.py
 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
class TooltipDrawer:
    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model

    @property
    def _super(self):
        """Return proxy for calling QCommonStyle methods on style_inst."""
        from ..style import AYONStyle as _AYONStyle

        return super(_AYONStyle, self.style_inst)

    @property
    def base_class(self):
        return {"QToolTip": QToolTip}

    def register_drawers(self):
        return {
            enum_to_str(
                QStyle.ControlElement,
                QStyle.ControlElement.CE_ShapedFrame,
                "QToolTip",
            ): self.draw_control,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_PanelTipLabel,
                "QToolTip",
            ): partial(
                self.draw_primitive, QStyle.PrimitiveElement.PE_PanelTipLabel
            ),
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_Frame,
                "QToolTip",
            ): partial(self.draw_primitive, QStyle.PrimitiveElement.PE_Frame),
        }

    def register_sizers(self):
        return {
            enum_to_str(
                QStyle.SubElement,
                QStyle.SubElement.SE_ShapedFrameContents,
                "QToolTip",
            ): self.get_rect,
            enum_to_str(
                QStyle.SubElement,
                QStyle.SubElement.SE_FrameLayoutItem,
                "QToolTip",
            ): self.get_rect,
        }

    def draw_control(
        self,
        option: QStyleOptionFrame,
        painter: QPainter,
        widget: QWidget,
    ):
        option.frameShadow = QFrame.Shadow.Plain
        option.frameShape = QFrame.Shape.StyledPanel
        self._super.drawControl(
            QStyle.ControlElement.CE_ShapedFrame, option, painter, widget
        )

    def draw_primitive(
        self,
        prim: QStyle.PrimitiveElement,
        option: QStyleOption,
        painter: QPainter,
        w: QWidget,
    ) -> None:
        if prim == QStyle.PrimitiveElement.PE_Frame:
            painter.save()
            painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
            style = self.model.get_style("QToolTip")
            style.set_context(w)
            # QColor(...) wrapping is required - PySide2's QPen/QBrush
            # constructors don't implicitly convert a plain hex string
            # like PySide6's do, and silently produce an invisible pen.
            pen = QPen(QColor(style["border-color"]))
            pen.setWidth(style["border-width"])
            painter.setBrush(Qt.BrushStyle.NoBrush)
            painter.setPen(pen)
            radius = int(style["border-radius"])
            painter.drawRoundedRect(
                option.rect,
                radius,
                radius,
            )
            painter.restore()

        elif prim == QStyle.PrimitiveElement.PE_PanelTipLabel:
            painter.save()
            painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
            style = self.model.get_style("QToolTip")
            style.set_context(w)
            brush = QBrush(QColor(style["background-color"]))
            painter.setBrush(brush)
            painter.setPen(Qt.PenStyle.NoPen)
            radius = int(style["border-radius"])
            painter.drawRoundedRect(
                option.rect,
                radius,
                radius,
            )
            painter.restore()

    def get_rect(
        self,
        element: QStyle.SubElement,
        option: QStyleOption,
        widget: QWidget,
    ) -> QRect:
        tt_style = self.model.get_style("QToolTip")
        tt_style.set_context(widget)
        tt_pad_x, tt_pad_y = tt_style["padding"]

        if element == QStyle.SubElement.SE_ShapedFrameContents:
            if isinstance(option, QStyleOptionFrame):
                option.features = QStyleOptionFrame.FrameFeature.Rounded
                option.frameShape = QFrame.Shape.StyledPanel
                widget.setContentsMargins(
                    tt_pad_x, tt_pad_y, tt_pad_x, tt_pad_y
                )

        elif element == QStyle.SubElement.SE_FrameLayoutItem:
            if isinstance(option, QStyleOptionFrame):
                option.features = QStyleOptionFrame.FrameFeature.Rounded
                option.frameShape = QFrame.Shape.StyledPanel
                widget.setContentsMargins(
                    tt_pad_x, tt_pad_y, tt_pad_x, tt_pad_y
                )

        return self._super.subElementRect(element, option, widget)

TreeViewDrawer

AYONStyle drawer for QTreeView.

Handles branch expand/collapse indicators and the indentation metric using colours from the QTreeView style data in ayon_style.json.

Source code in client/ayon_core/ui/drawers/tree_view.py
 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
class TreeViewDrawer:
    """AYONStyle drawer for QTreeView.

    Handles branch expand/collapse indicators and the indentation metric
    using colours from the QTreeView style data in ayon_style.json.
    """

    def __init__(self, style_inst: AYONStyle) -> None:
        self.style_inst = style_inst
        self.model = style_inst.model
        self._icon_cache = {}

    @property
    def base_class(self):
        return {"QTreeView": QTreeView}

    def register_drawers(self) -> dict:
        """Register drawing functions for QTreeView primitives."""
        return {
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_IndicatorBranch,
                "QTreeView",
            ): self.draw_branch_indicator,
            enum_to_str(
                QStyle.PrimitiveElement,
                QStyle.PrimitiveElement.PE_PanelScrollAreaCorner,
                "QTreeView",
            ): self.draw_scrollbar_corner,
        }

    def register_metrics(self) -> dict:
        """Register pixel metric functions for QTreeView."""
        return {
            enum_to_str(
                QStyle.PixelMetric,
                QStyle.PixelMetric.PM_TreeViewIndentation,
                "QTreeView",
            ): self.get_metric,
        }

    def get_metric(
        self,
        metric: QStyle.PixelMetric,
        opt: QStyleOption | None = None,
        widget: QWidget | None = None,
    ) -> int:
        """Return indent width from style data.

        Args:
            metric: The pixel metric being queried.
            opt: Optional style option.
            widget: The target widget.

        Returns:
            The indent size in pixels.
        """
        if metric == QStyle.PixelMetric.PM_TreeViewIndentation:
            variant = getattr(widget, "_variant_str", "default")
            style = self.model.get_style("QTreeView", variant)
            return int(style.get("indent", 20))
        return 0

    def _draw_cell_border(
        self,
        painter: QPainter,
        rect: QRect,
        style: dict,
    ) -> None:
        """Draw top and bottom border lines for an AYTableView cell."""
        painter.setPen(
            QPen(
                QColor(style.get("border-color")), style.get("border-width", 1)
            )
        )
        painter.setBrush(Qt.BrushStyle.NoBrush)
        painter.drawLines(
            [
                rect.topLeft(),
                rect.topRight(),
                rect.bottomLeft(),
                rect.bottomRight(),
            ]
        )

    def _resolve_tree_view(self, widget: QWidget | None) -> QWidget | None:
        """Resolve widget to the actual QTreeView/AYTableView."""
        if widget is not None and not isinstance(widget, QTreeView):
            return widget.parent() or widget
        return widget

    def _paint_cell_background(
        self,
        painter: QPainter,
        rect: QRect,
        style: dict,
        is_table: bool,
        is_base_state: bool = False,
    ) -> None:
        """Paint background fill and optional cell borders.

        Args:
            painter: The QPainter to draw on.
            rect: The rectangle to fill.
            style: The style data dictionary.
            is_table: Whether this is an AYTableView cell.
            is_base_state: If True and is_table, use 'background-color-item'.
        """
        painter.save()
        if is_table and is_base_state:
            bg_key = "background-color-item"
        else:
            bg_key = "background-color"
        painter.fillRect(rect, QColor(style.get(bg_key, "transparent")))
        if is_table:
            self._draw_cell_border(painter, rect, style)
        painter.restore()

    def _paint_icon(
        self,
        painter: QPainter,
        rect: QRect,
        icon,
        icon_size: int | None,
    ) -> None:
        """Paint a cached icon, optionally resizing and repositioning it."""
        draw_rect = QRect(rect)
        if icon_size is not None:
            center = rect.center()
            draw_rect.setSize(QSize(icon_size, icon_size))
            draw_rect.moveTo(
                rect.right() - icon_size, center.y() - icon_size // 2
            )
        icon.paint(painter, draw_rect)

    def _paint_fallback_arrow(
        self,
        painter: QPainter,
        rect: QRect,
        color: QColor,
        is_open: bool,
    ) -> None:
        """Paint a geometric triangle arrow when no icon is configured."""
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(QBrush(color))

        cx, cy = rect.center().x(), rect.center().y()
        size = max(4, min(rect.width(), rect.height()) // 3)

        path = QPainterPath()
        if is_open:
            path.moveTo(cx - size, cy - size // 2)
            path.lineTo(cx + size, cy - size // 2)
            path.lineTo(cx, cy + size // 2)
        else:
            path.moveTo(cx - size // 2, cy - size)
            path.lineTo(cx - size // 2, cy + size)
            path.lineTo(cx + size // 2, cy)
        path.closeSubpath()
        painter.drawPath(path)

    def draw_branch_indicator(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        """Draw expand / collapse arrows for tree branch items.

        Args:
            option: The primitive element style option.
            painter: The QPainter to draw on.
            widget: The QTreeView widget (may be the viewport).
        """
        has_children = bool(option.state & QStyle.StateFlag.State_Children)
        tv = self._resolve_tree_view(widget)
        is_table = type(tv).__name__ == "AYTableView"
        is_selected = bool(option.state & QStyle.StateFlag.State_Selected)
        is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
        variant = getattr(tv, "_variant_str", "default")

        state_name = (
            "selected" if is_selected else "hover" if is_hovered else "base"
        )

        widget_class = "AYTableView" if is_table else "QTreeView"
        t_style = self.model.get_style(
            widget_class, variant=variant, state=state_name
        )

        # Items without children only need background/border painting
        if not has_children:
            self._paint_cell_background(
                painter,
                option.rect,
                t_style,
                is_table,
                is_base_state=(state_name == "base"),
            )
            return

        is_open = bool(option.state & QStyle.StateFlag.State_Open)
        color = QColor(t_style.get("branch-indicator-color", "#8b9198"))
        icon_name = t_style.get(
            "expanded-icon-name" if is_open else "expand-icon-name"
        )

        # Paint background for items with children
        self._paint_cell_background(painter, option.rect, t_style, is_table)

        if icon_name:
            key = f"{icon_name}-{color.name()}"
            if key not in self._icon_cache:
                self._icon_cache[key] = get_icon(icon_name, color=color)
            icon_size = t_style.get("expand-icon-size")
            self._paint_icon(
                painter, option.rect, self._icon_cache[key], icon_size
            )
        else:
            self._paint_fallback_arrow(painter, option.rect, color, is_open)

    def draw_scrollbar_corner(
        self,
        option: QStyleOption,
        painter: QPainter,
        widget: QWidget | None = None,
    ) -> None:
        style = self.model.get_style("QScrollArea", variant="default")
        style.set_context(widget)
        painter.save()
        # Draw corner background
        bg = style.get("background-color", "transparent")
        painter.fillRect(option.rect, QColor(bg))

        painter.restore()

draw_branch_indicator(option, painter, widget=None)

Draw expand / collapse arrows for tree branch items.

Parameters:

Name Type Description Default
option QStyleOption

The primitive element style option.

required
painter QPainter

The QPainter to draw on.

required
widget QWidget | None

The QTreeView widget (may be the viewport).

None
Source code in client/ayon_core/ui/drawers/tree_view.py
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
def draw_branch_indicator(
    self,
    option: QStyleOption,
    painter: QPainter,
    widget: QWidget | None = None,
) -> None:
    """Draw expand / collapse arrows for tree branch items.

    Args:
        option: The primitive element style option.
        painter: The QPainter to draw on.
        widget: The QTreeView widget (may be the viewport).
    """
    has_children = bool(option.state & QStyle.StateFlag.State_Children)
    tv = self._resolve_tree_view(widget)
    is_table = type(tv).__name__ == "AYTableView"
    is_selected = bool(option.state & QStyle.StateFlag.State_Selected)
    is_hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
    variant = getattr(tv, "_variant_str", "default")

    state_name = (
        "selected" if is_selected else "hover" if is_hovered else "base"
    )

    widget_class = "AYTableView" if is_table else "QTreeView"
    t_style = self.model.get_style(
        widget_class, variant=variant, state=state_name
    )

    # Items without children only need background/border painting
    if not has_children:
        self._paint_cell_background(
            painter,
            option.rect,
            t_style,
            is_table,
            is_base_state=(state_name == "base"),
        )
        return

    is_open = bool(option.state & QStyle.StateFlag.State_Open)
    color = QColor(t_style.get("branch-indicator-color", "#8b9198"))
    icon_name = t_style.get(
        "expanded-icon-name" if is_open else "expand-icon-name"
    )

    # Paint background for items with children
    self._paint_cell_background(painter, option.rect, t_style, is_table)

    if icon_name:
        key = f"{icon_name}-{color.name()}"
        if key not in self._icon_cache:
            self._icon_cache[key] = get_icon(icon_name, color=color)
        icon_size = t_style.get("expand-icon-size")
        self._paint_icon(
            painter, option.rect, self._icon_cache[key], icon_size
        )
    else:
        self._paint_fallback_arrow(painter, option.rect, color, is_open)

get_metric(metric, opt=None, widget=None)

Return indent width from style data.

Parameters:

Name Type Description Default
metric PixelMetric

The pixel metric being queried.

required
opt QStyleOption | None

Optional style option.

None
widget QWidget | None

The target widget.

None

Returns:

Type Description
int

The indent size in pixels.

Source code in client/ayon_core/ui/drawers/tree_view.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def get_metric(
    self,
    metric: QStyle.PixelMetric,
    opt: QStyleOption | None = None,
    widget: QWidget | None = None,
) -> int:
    """Return indent width from style data.

    Args:
        metric: The pixel metric being queried.
        opt: Optional style option.
        widget: The target widget.

    Returns:
        The indent size in pixels.
    """
    if metric == QStyle.PixelMetric.PM_TreeViewIndentation:
        variant = getattr(widget, "_variant_str", "default")
        style = self.model.get_style("QTreeView", variant)
        return int(style.get("indent", 20))
    return 0

register_drawers()

Register drawing functions for QTreeView primitives.

Source code in client/ayon_core/ui/drawers/tree_view.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def register_drawers(self) -> dict:
    """Register drawing functions for QTreeView primitives."""
    return {
        enum_to_str(
            QStyle.PrimitiveElement,
            QStyle.PrimitiveElement.PE_IndicatorBranch,
            "QTreeView",
        ): self.draw_branch_indicator,
        enum_to_str(
            QStyle.PrimitiveElement,
            QStyle.PrimitiveElement.PE_PanelScrollAreaCorner,
            "QTreeView",
        ): self.draw_scrollbar_corner,
    }

register_metrics()

Register pixel metric functions for QTreeView.

Source code in client/ayon_core/ui/drawers/tree_view.py
48
49
50
51
52
53
54
55
56
def register_metrics(self) -> dict:
    """Register pixel metric functions for QTreeView."""
    return {
        enum_to_str(
            QStyle.PixelMetric,
            QStyle.PixelMetric.PM_TreeViewIndentation,
            "QTreeView",
        ): self.get_metric,
    }

do_nothing(*args, **kwargs)

No-op stub used to suppress default Qt drawing for certain elements.

Source code in client/ayon_core/ui/drawers/_utils.py
14
15
def do_nothing(*args, **kwargs):
    """No-op stub used to suppress default Qt drawing for certain elements."""

enum_to_str(enum, enum_value, widget)

Convert enum value to string representation.

Source code in client/ayon_core/ui/drawers/_utils.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def enum_to_str(enum, enum_value: int, widget: str) -> str:
    """Convert enum value to string representation."""
    cachekey = f"{enum.__name__}_{enum_value}_{widget}"
    if not hasattr(enum_to_str, "_cache"):
        enum_to_str._cache = {}  # type: ignore
    value: str | None = enum_to_str._cache.get(cachekey)
    if value is not None:
        return value

    if hasattr(enum, "valueToKey"):
        value = enum.valueToKey(enum_value)
    else:
        meta_object = QStyle.staticMetaObject
        enum_index = meta_object.indexOfEnumerator(enum.__name__)
        meta_enum = meta_object.enumerator(enum_index)
        value = f"{meta_enum.valueToKey(enum_value)}-{widget}"

    enum_to_str._cache[cachekey] = value

    return value

style_font(style, w)

Create a QFont from a style dictionary.

Parameters:

Name Type Description Default
style dict

A dict with font-family, font-size, font-weight keys.

required
w QWidget | None

Optional widget (unused, kept for API consistency).

required

Returns:

Type Description
QFont

Configured QFont instance.

Source code in client/ayon_core/ui/drawers/_utils.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def style_font(style: dict, w: QWidget | None) -> QFont:
    """Create a QFont from a style dictionary.

    Args:
        style: A dict with font-family, font-size, font-weight keys.
        w: Optional widget (unused, kept for API consistency).

    Returns:
        Configured QFont instance.

    """
    font = QFont()
    font.setHintingPreference(QFont.HintingPreference.PreferNoHinting)
    font.setFamily(style["font-family"])
    font.setPointSizeF(style["font-size"])
    font.setWeight(QFont.Weight(style["font-weight"]))
    return font