找出是否使用self.sender()

时间:2017-04-23 15:59:00

标签: python python-2.7 qt pyqt

QPushButton lightsBtn是一个切换按钮,用于打开和关闭灯光。当用户按下lightsBtn时,功能lightsBtnHandler将检查该按钮当前是否已被选中,并拨打turnOnLightsturnOffLights

我认为self.sender()能够访问QPushButton的属性,但我无法找到有关访问已检查状态的任何文档。

有可能吗?

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()

1 个答案:

答案 0 :(得分:1)

根据@Matho评论,我已经修改了一些代码。

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_())