# Copyright (C) 2026 Seth Hillbrand # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """iOS-style toggle switch widget.""" from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, Property, QRectF from PySide6.QtWidgets import QWidget from PySide6.QtGui import QPainter, QColor from ..theme import COLOR_ACCENT, COLOR_TOGGLE_OFF class ToggleSwitch(QWidget): """Custom painted toggle switch. Pink when on, gray when off.""" toggled = Signal(bool) TRACK_W = 44 TRACK_H = 22 THUMB_RADIUS = 8 THUMB_MARGIN = 3 def __init__(self, checked: bool = False, parent=None): super().__init__(parent) self._checked = checked self._thumb_pos = float(self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS if checked else self.THUMB_MARGIN + self.THUMB_RADIUS) self.setFixedSize(self.TRACK_W, self.TRACK_H) self.setCursor(Qt.CursorShape.PointingHandCursor) self._anim = QPropertyAnimation(self, b"thumb_pos") self._anim.setDuration(150) self._anim.setEasingCurve(QEasingCurve.Type.InOutQuad) def _get_thumb_pos(self) -> float: return self._thumb_pos def _set_thumb_pos(self, val: float): self._thumb_pos = val self.update() thumb_pos = Property(float, _get_thumb_pos, _set_thumb_pos) def is_checked(self) -> bool: return self._checked def set_checked(self, checked: bool, emit: bool = True): if self._checked == checked: return self._checked = checked target = (self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS if checked else self.THUMB_MARGIN + self.THUMB_RADIUS) self._anim.stop() self._anim.setStartValue(self._thumb_pos) self._anim.setEndValue(float(target)) self._anim.start() if emit: self.toggled.emit(checked) def mousePressEvent(self, event): if event.button() == Qt.MouseButton.LeftButton: self.set_checked(not self._checked) def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.RenderHint.Antialiasing) track_color = QColor(COLOR_ACCENT) if self._checked else QColor(COLOR_TOGGLE_OFF) p.setPen(Qt.PenStyle.NoPen) p.setBrush(track_color) p.drawRoundedRect(QRectF(0, 0, self.TRACK_W, self.TRACK_H), self.TRACK_H / 2, self.TRACK_H / 2) p.setBrush(QColor("#ffffff")) p.drawEllipse(QRectF(self._thumb_pos - self.THUMB_RADIUS, (self.TRACK_H - 2 * self.THUMB_RADIUS) / 2, 2 * self.THUMB_RADIUS, 2 * self.THUMB_RADIUS)) p.end()