Search code examples
pythonqtstylesheetspyside6

My qss selector doesn't work with a correct ID selected


I am learning QSS these days. There is a situation that I want to use the selector to change a QPushButton widget but not the others. So I write the qss file as blow

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

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

And my py file is as blow

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

But the selector seems not working. The final window is as blow:

the window

It seems that the gloabal configuration has been worked, but the selected button button_3 has no effect.

Why does this happen? I think the issue might be on the private variable in class but I am not for sure.


Solution

  • The HTML id is equivalent to the objectName property in Qt so add:

    self.button_3.setObjectName("button_3")