简体   繁体   English

PyQt5 QPushButton setSyleSheet 按下时不改变按钮颜色

[英]PyQt5 QPushButton setSyleSheet does not change button color when pressed

After studying various examples in this forum, I tried to change the color of a button when pressed.在研究了这个论坛中的各种示例之后,我尝试更改按钮按下时的颜色。 The button is normally blue, and when it is pressed I want it to turn red.该按钮通常是蓝色的,当按下它时我希望它变成红色。 The following code does display a blue button with white text, but it does not change to red when pressed.以下代码确实显示了一个带有白色文本的蓝色按钮,但按下时它不会变为红色。 Please advise.请指教。 I'm fairly new to learning python/pyqt5.我对学习 python/pyqt5 还是很陌生。

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

class Push_button(QPushButton):
    def __init__(self, parent=None):
        super(Push_button, self).__init__(parent)
        self.setStyleSheet("background-color: rgb(0,0,255); color: rgb(255,255,255); \
                  pressed {background-color : rgb(255,0,0); color: rgb(255,255,255);} ")

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.myButton = Push_button(self)
        self.myButton.setText("myButton")
        self.myButton.clicked.connect(self.myButtonClicked)

    def myButtonClicked(self):
        print("myButtonClicked")
 
if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = MyWindow()
    w.show()

    sys.exit(app.exec_())

You are not using selectors correctly.您没有正确使用选择器。

Right now your stylesheet sets the blue background color universally , and the red color for classes named "pressed".现在,您的样式表普遍设置蓝色背景颜色,并为名为“pressed”的设置红色。

        self.setStyleSheet('''
            QPushButton {
                background-color: rgb(0,0,255); color: rgb(255,255,255);
            }
            QPushButton:pressed {
                background-color : rgb(255,0,0); color: rgb(255,255,255);
            }
        ''')

Read more about selector types in the official documentation.在官方文档中阅读有关选择器类型的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM