检查PyQt QPushButton是否使用自我发送者()

2024-10-01 13:33:12 发布

您现在位置:Python中文网/ 问答频道 /正文

QPushButtonlightsBtn是一个开关按钮,用于开关灯。当用户按下lightsBtn时,函数lightsBtnHandler将检查按钮当前是否被选中,并调用turnOnLights或{}。在

我认为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()

Tags: 函数用户self属性状态def按钮sender
1条回答
网友
1楼 · 发布于 2024-10-01 13:33:12

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

相关问题 更多 >