Nyxynyx
Nyxynyx

Reputation: 63687

Find out whether PyQt QPushButton is checked using self.sender()

The QPushButton lightsBtn is a toggle button that switches a light on and off. When the user presses lightsBtn, the function lightsBtnHandler will check whether the button is currently checked or not and calls either turnOnLights or turnOffLights.

I think self.sender() is able to access properties of the QPushButton, but I cant find any documentation on accessing the checked state.

Is it possible?

class Screen(QMainWindow):

    def initUI(self):
        lightsBtn= QPushButton('Turn On')
        lightsBtn.setCheckable(True)  
        lightsBtn.setStyleSheet("QPushButton:checked {color: white; background-color: green;}")
        lightsBtn.clicked.connect(self.lightsBtnHandler)
        lightsBtn.show()

    def lightsBtnHandler(self):
        if self.sender().?? isChecked():    # How to check for checked state?
            self.turnOnLights()
        else:
            self.turnOffLights()

Upvotes: 2

Views: 14102

Answers (1)

Luchko
Luchko

Reputation: 1153

following the @Matho comment I have modified your code a little bit.

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
import sys

class Screen(QMainWindow):
    def __init__(self):
        super(Screen, self).__init__()
        self.initUI()

    def initUI(self):
        self.lightsBtn= QPushButton('Turn On')
        self.lightsBtn.setCheckable(True)  
        self.lightsBtn.setStyleSheet("QPushButton:checked {color: white; background-color: green;}")
        self.lightsBtn.clicked.connect(self.lightsBtnHandler)

        # probaply you will want to set self.lightsBtn 
        # at certain spot using layouts
        self.setCentralWidget(self.lightsBtn)

    def lightsBtnHandler(self):
        if self.lightsBtn.isChecked():
            self.turnOnLights()
        else:
            self.turnOffLights()

    def turnOnLights(self):
        print("truned on")

    def turnOffLights(self):
        print("truned off")

app = QApplication(sys.argv)
window = Screen()
window.show()
sys.exit(app.exec_())

Upvotes: 4

Related Questions