Mar-05-2024, 04:20 PM
QPushButton has an isClhecked() method that can be used to check the checked state of the button. This is available even if you don't call button.setCheckable(True). setCheckable(True) enables toggle behavior for the button but does not add any attributes/variables. When checkable, the button's isChecked() state toggles between True and False when the button is pressed, and the button calls functions attached to the "toggle" signal.
You can see this if you run the example below.
You can see this if you run the example below.
from PySide6.QtWidgets import (QApplication, QMainWindow, QPushButton) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.counter = 0 self.toggle = False self.button = QPushButton("Not Checkable") self.button.setCheckable(self.toggle) self.button .clicked.connect(self.clicked_cb) self.button .clicked.connect(self.clicked_with_toggle_cb) self.button.toggled.connect(self.toggled_cb) # Set the central widget of the Window. self.setCentralWidget(self.button) def clicked_cb(self): self.counter += 1 if self.counter >= 3: self.counter = 0 self.toggle = not self.toggle self.button.setCheckable(self.toggle) self.button.setText("Checkable" if self.toggle else "Not Checkable") def clicked_with_toggle_cb(self, checked): print("Clicked with toggle state", checked) def toggled_cb(self, checked): print("Toggled", checked) app = QApplication() window = MainWindow() window.show() app.exec()This program toggles the toggle state after three presses of the button. You can see that the clicked_with_toggle_cb is always called when the button is pressed, but the isChecked() state is always False when the button is not checkable. Also notice that the toggled_cb is only called thwne the button is checkable.