Skip to content

checkbox

CheckboxDrawer: custom painting for QCheckBox (toggle switch).

CheckboxDrawer

Source code in client/ayon_ui_qt/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
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")
        style = self.model.get_style(
            "QCheckBox",
            variant=variant,
            state="checked" if checked else "base",
        )
        style.set_context(w)

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

        # draw toggle knob
        painter.setBrush(QColor(style["indicator-color"]))
        offset = frame_rect.height() * 0.125
        state_rect: QRectF = frame_rect.adjusted(
            offset, offset, -offset, -offset
        )
        state_rect.setWidth(state_rect.height())
        if checked:
            state_rect.moveRight(frame_rect.right() - offset)
        painter.drawEllipse(state_rect)

        painter.restore()