首页 > 解决方案 > 我的 qss 选择器不适用于选择了正确的 ID

问题描述

这些天我正在学习QSS。有一种情况是我想使用选择器来更改 QPushButton 小部件而不是其他小部件。所以我把qss文件写成打击

QPushButton#button_3 {
    background: yellow;
    min-width: 3em;
    min-height: 2em;
}

QPushButton {
    background-color: red;
    min-width: 30em;
    border-style: outset;
    border-width: 2px;
}

我的 py 文件也很糟糕

import sys

from PySide6.QtWidgets import (QApplication, QVBoxLayout, QWidget, QPushButton, QGridLayout, QLabel)
from PySide6 import QtCore

class Form(QWidget):
    def __init__(self):
        super(Form,self).__init__()

        self.layout = QVBoxLayout()
        
        self.button_1 = QPushButton("button_1")
        self.button_2 = QPushButton("button_2")
        self.button_3 = QPushButton("button_3")

        self.layout.addWidget(self.button_1)
        self.layout.addWidget(self.button_2)
        self.layout.addWidget(self.button_3)

        self.setLayout(self.layout)

        '''
        with open("./style/button.qss", "r") as f:
            _style = f.read()
            self.setStyleSheet(_style)
        '''


if __name__ == "__main__":
    app = QApplication([])

    myForm = Form()
    myForm.show()

    with open("./style/button.qss", "r") as f:
            _style = f.read()
            myForm.setStyleSheet(_style)

    sys.exit(app.exec())

但是选择器似乎不起作用。最后的窗口是打击:

窗户

似乎全局配置已经生效,但是选中的按钮button_3没有效果。

为什么会这样?我认为问题可能出在课堂上的私有变量上,但我不确定。

标签: pythonqtstylesheetspyside6

解决方案


HTML id 等同objectName于 Qt 中的属性,因此添加:

self.button_3.setObjectName("button_3")

推荐阅读