1

I found the following tutorial https://www.pythonguis.com/widgets/pyqt-toggle-widget/ and was able to create a Toggle widget, but I don't know how to detect the value changes.

Can you please tell me how to detect toggle value change in below code:

import PyQt5
from PyQt5 import QtWidgets
from qtwidgets import Toggle, AnimatedToggle

class Window(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        toggle_1 = Toggle()
        toggle_2 = AnimatedToggle(
            checked_color="#FFB000",
            pulse_checked_color="#44FFB000"
        )

        container = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(toggle_1)
        layout.addWidget(toggle_2)
        container.setLayout(layout)

        self.setCentralWidget(container)


app = QtWidgets.QApplication([])
w = Window()
w.show()
app.exec_()
hashy
  • 175
  • 10

1 Answers1

3

The Toggle and AnimatedToggle is a QCheckBox with a custom painting, so if you want to detect when the state changes use the toggled signal.

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        toggle_1 = Toggle()
        toggle_2 = AnimatedToggle(
            checked_color="#FFB000", pulse_checked_color="#44FFB000"
        )

        toggle_1.toggled.connect(self.handle_toggled)
        toggle_2.toggled.connect(self.handle_toggled)

        container = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(toggle_1)
        layout.addWidget(toggle_2)
        container.setLayout(layout)

        self.setCentralWidget(container)

    def handle_toggled(self, state):
        print(state)
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • you make me look such a bad programmer. anyway, thanks it worked :) – hashy Sep 08 '21 at 03:17
  • @hashy, On a side note, `toggle` also has `isChecked()` method, that you can use through out the application if you want to check the state of the toggle. It returns `True`/`False` value based on the current state. – ThePyGuy Sep 08 '21 at 03:20