Module QFlow.components.toggleSwitch.toggleSwitch

This module defines the ToggleSwitch class, a customizable animated toggle switch widget for PyQt-PySide.

The class provides a clickable switch that toggles between ON and OFF states with smooth animations. It supports color customization and state querying.

Classes

class ToggleSwitch (parent,
width: int = 50,
height: int = 25,
bgColor: list[str] = ['#ccc', '#00c853'],
circleColor: str = '#fff',
checked: bool = False)
Expand source code
class ToggleSwitch(QWidget):
    """
    Represents a custom animated toggle switch.

    This widget mimics a modern switch with animation and customizable colors.
    The circle smoothly slides between ON and OFF states upon click, and
    emits visual feedback based on the internal boolean state.
    """

    def __init__(
            self, 
            parent, 
            width: int = 50, 
            height: int = 25,
            # num ≠ 0 ⇔ True: It's the same as on or off
            bgColor: list[str] = ['#ccc', '#00c853'],
            circleColor: str = '#fff',
            checked: bool = False
        ):
        """
        Initializes the ToggleSwitch object.

        Args:
            parent (QWidget): The parent widget.
            width (int, optional): The width of the toggle. Default is 50.
            height (int, optional): The height of the toggle. Default is 25.
            bgColor (list, optional): List of two colors [offColor, onColor] in hex format.
            circleColor (str, optional): Color of the sliding circle in hex format.
        """
        super().__init__(parent)
        self.setFixedSize(width, height)
        self._checked = False
        self._circlePosition = 2

        self._animation = QPropertyAnimation(self, b"circlePosition")
        self._animation.setDuration(150)

        self._bgColorOn = QColor(bgColor[1])
        self._bgColorOff = QColor(bgColor[0])
        self._circleColor = QColor(circleColor)

        self.setChecked(checked)

        self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))

    def mousePressEvent(self, event):
        """
        Handles the mouse press event to toggle the switch state.

        Args:
            event (QMouseEvent): The mouse event.
        """
        self._checked = not self._checked
        self._animate()
        self.update()
        super().mousePressEvent(event)

    def _animate(self):
        """
        Performs the circle sliding animation based on the current state.
        """
        start = self._circlePosition
        end = self.width() - self.height() + 2 if self._checked else 2
        self._animation.stop()
        self._animation.setStartValue(start)
        self._animation.setEndValue(end)
        self._animation.start()

    def paintEvent(self, event):
        """
        Paints the switch background and sliding circle.

        Args:
            event (QPaintEvent): The paint event.
        """
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        bg_color = self._bgColorOn if self._checked else self._bgColorOff
        painter.setBrush(QBrush(bg_color))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() / 2, self.height() / 2)

        painter.setBrush(QBrush(self._circleColor))
        painter.drawEllipse(self._circlePosition, 2, self.height() - 4, self.height() - 4)

    def isChecked(self):
        """
        Returns:
            bool: The current checked state of the switch.
        """
        return self._checked

    def setChecked(self, checked: bool):
        """
        Sets the checked state of the switch and updates its position immediately.

        Args:
            checked (bool): The desired checked state.
        """
        self._checked = checked
        self._animate()
        self.update()

    def getCirclePosition(self):
        """
        Returns:
            int: The current X position of the circle.
        """
        return self._circlePosition

    def setCirclePosition(self, pos):
        """
        Updates the X position of the circle (used by the animation).

        Args:
            pos (int): The new position.
        """
        self._circlePosition = pos
        self.update()

    circlePosition = Property(int, fget=getCirclePosition, fset=setCirclePosition)

Represents a custom animated toggle switch.

This widget mimics a modern switch with animation and customizable colors. The circle smoothly slides between ON and OFF states upon click, and emits visual feedback based on the internal boolean state.

Initializes the ToggleSwitch object.

Args

parent : QWidget
The parent widget.
width : int, optional
The width of the toggle. Default is 50.
height : int, optional
The height of the toggle. Default is 25.
bgColor : list, optional
List of two colors [offColor, onColor] in hex format.
circleColor : str, optional
Color of the sliding circle in hex format.

Ancestors

  • PyQt6.QtWidgets.QWidget
  • PyQt6.QtCore.QObject
  • PyQt6.sip.wrapper
  • PyQt6.QtGui.QPaintDevice
  • PyQt6.sip.simplewrapper

Instance variables

var circlePosition

pyqtProperty(type, fget=None, fset=None, freset=None, fdel=None, doc=None, designable=True, scriptable=True, stored=True, user=False, constant=False, final=False, notify=None, revision=0) -> property attribute

type is the type of the property. It is either a type object or a string that is the name of a C++ type. freset is a function for resetting an attribute to its default value. designable sets the DESIGNABLE flag (the default is True for writable properties and False otherwise). scriptable sets the SCRIPTABLE flag. stored sets the STORED flag. user sets the USER flag. constant sets the CONSTANT flag. final sets the FINAL flag. notify is the NOTIFY signal. revision is the REVISION. The other parameters are the same as those required by the standard Python property type. Properties defined using pyqtProperty behave as both Python and Qt properties. Decorators can be used to define new properties or to modify existing ones.

Methods

def getCirclePosition(self)
Expand source code
def getCirclePosition(self):
    """
    Returns:
        int: The current X position of the circle.
    """
    return self._circlePosition

Returns

int
The current X position of the circle.
def isChecked(self)
Expand source code
def isChecked(self):
    """
    Returns:
        bool: The current checked state of the switch.
    """
    return self._checked

Returns

bool
The current checked state of the switch.
def mousePressEvent(self, event)
Expand source code
def mousePressEvent(self, event):
    """
    Handles the mouse press event to toggle the switch state.

    Args:
        event (QMouseEvent): The mouse event.
    """
    self._checked = not self._checked
    self._animate()
    self.update()
    super().mousePressEvent(event)

Handles the mouse press event to toggle the switch state.

Args

event : QMouseEvent
The mouse event.
def paintEvent(self, event)
Expand source code
def paintEvent(self, event):
    """
    Paints the switch background and sliding circle.

    Args:
        event (QPaintEvent): The paint event.
    """
    painter = QPainter(self)
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)

    bg_color = self._bgColorOn if self._checked else self._bgColorOff
    painter.setBrush(QBrush(bg_color))
    painter.setPen(Qt.PenStyle.NoPen)
    painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() / 2, self.height() / 2)

    painter.setBrush(QBrush(self._circleColor))
    painter.drawEllipse(self._circlePosition, 2, self.height() - 4, self.height() - 4)

Paints the switch background and sliding circle.

Args

event : QPaintEvent
The paint event.
def setChecked(self, checked: bool)
Expand source code
def setChecked(self, checked: bool):
    """
    Sets the checked state of the switch and updates its position immediately.

    Args:
        checked (bool): The desired checked state.
    """
    self._checked = checked
    self._animate()
    self.update()

Sets the checked state of the switch and updates its position immediately.

Args

checked : bool
The desired checked state.
def setCirclePosition(self, pos)
Expand source code
def setCirclePosition(self, pos):
    """
    Updates the X position of the circle (used by the animation).

    Args:
        pos (int): The new position.
    """
    self._circlePosition = pos
    self.update()

Updates the X position of the circle (used by the animation).

Args

pos : int
The new position.