These advertisements helps me to keep writing articles on this website

Qt stylesheet (CSS) with ID selector

Qt Stylesheets are inherited down the visual tree. Putting a border on a Frame will put a border on all Frame subclasses down the visual tree. This example shows how to apply a stylesheet to a widget with a certain id.

I am using pyside 6 with from __feature__ import snake_case, true_property. That is why I can use the style_sheet = ... syntax. Here is a app-wide style for QLabels:

app.style_sheet = """
    QLabel {
        margin: 80px;
        border: 5px solid #000;
        font-size: 40px;
        background-color: #900;
        color: #fff;
        font-weight: bold;
    }"""

The style is applied on all labels. And this is what it looks like:

all

What if you want to set the style only to the first label?

Use id selection in Qt

To use id selection you have to do two things:

  1. Set the widgets object_name
  2. Use the object_name in the style

Here is a full example:

import sys
from PySide6.QtWidgets import QWidget
from PySide6.QtWidgets import QApplication
from PySide6.QtWidgets import QMainWindow
from PySide6.QtWidgets import QStyle
from PySide6.QtWidgets import QLabel
from PySide6.QtWidgets import QSizePolicy
from PySide6.QtWidgets import QVBoxLayout
from PySide6.QtCore import Qt
from PySide6.QtCore import QSize
from __feature__ import snake_case, true_property

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        centralwidget = QWidget()
        self.set_central_widget(centralwidget)
        self.geometry = QStyle.aligned_rect(Qt.LeftToRight, Qt.AlignCenter, QSize(800, 600), QApplication.primary_screen.available_geometry)

        label1 = QLabel("I must have left my house at eight, because I always do.")
        label1.alignment = Qt.AlignCenter
        label1.word_wrap = True
        label1.object_name = "label1"

        label2 = QLabel("I must have left my house at eight, because I always do.")
        label2.alignment = Qt.AlignCenter
        label2.word_wrap = True

        verticalbox = QVBoxLayout()
        verticalbox.add_widget(label1)
        verticalbox.add_widget(label2)
        centralwidget.set_layout(verticalbox)

app = QApplication(sys.argv)

app.style_sheet = """
    QLabel#label1 {
        margin: 80px;
        border: 5px solid #000;
        font-size: 40px;
        background-color: #900;
        color: #fff;
        font-weight: bold;
    }"""

mainwindow = MainWindow()
mainwindow.show()

app.exec_()

And this is what it looks like. As you see, the style is only applied to the first label:

single style

Written by Loek van den Ouweland on January 13, 2021. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.