PySide6属性选择器设置样式避坑
总所周知,Qt中qss语法支持属性选择器,通过setProperty设置key和value,支持在多种样式之前切换。今天使用了一下PySide6的属性选择器,发现了一个问题。完整代码见最后。
首先,先写一段qss样式,用来设置按键样式。
QPushButton[state=True] {
	background: #3574f0;
}
QPushButton[state=False] {
	background:#e32018;
} 
然后,在按键的槽函数里写上属性切换。
def on_button_click():
    if button.property("state"):
        button.setProperty("state", False)
    else:
        button.setProperty("state", True)
    button.style().polish(button) 
千万不能忘记最后一句polish()。
最后,运行当前文件。

什么也没有发生!
经研究发现,在C++中,代码中使用小写true和false,qss同样使用的小写,所以惯性思维,Python中使用的是大写True和False,但qss中不能也写大写,应该继续使用小写true和false。
修改后的qss:
QPushButton[state=true] {
	background: #3574f0;
}
QPushButton[state=false] {
	background:#e32018;
} 
再次运行,结果如期望一样,可以切换样式。


完整代码:
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget
button = None
def on_button_click():
    if button.property("state"):
        button.setProperty("state", False)
    else:
        button.setProperty("state", True)
    button.style().polish(button)
if __name__ == '__main__':
    app = QApplication()
    mw = QMainWindow()
    mw.setCentralWidget(QWidget())
    mw.setFixedSize(240, 160)
    button = QPushButton(mw.centralWidget())
    button.setGeometry(80, 60, 80, 26)
    button.setText("click")
    button.setStyleSheet("QPushButton[state=true] {"
                         "background: #3574f0;"
                         "}"
                         "QPushButton[state=false] {"
                         "background:#e32018;"
                         "}")
    button.setProperty("state", False)
    button.clicked.connect(on_button_click)
    mw.show()
    sys.exit(app.exec()) 
                