PyQt give color to a specific element
Asked Answered
R

1

20

This might be an easy question, but I'm trying to give a color to a specific QLabel in my application and it doesn't work.

The code I tried is the following :

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet("QLabel#nom_plan_label {color: yellow}")

Any hint would be appreciated

Ravo answered 20/12, 2011 at 15:16 Comment(0)
L
34

There are a few things wrong with the stylesheet syntax you are using.

Firstly, ID selectors (i.e. #nom_plan_label) must refer to the objectName of the widget.

Secondly, it is only necessary to use selectors when a stylesheet is applied to an ancestor widget and you want certain style rules to cascade down to particular descendant widgets. If you're applying the stylesheet directly to one widget, the selector (and braces) can be left out.

Given the above two points, your example code would become either:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setObjectName('nom_plan_label')
nom_plan_label.setStyleSheet('QLabel#nom_plan_label {color: yellow}')

or, more simply:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet('color: yellow')
Legere answered 20/12, 2011 at 17:24 Comment(1)
The only possible time I think this solution would cause an issue is like you said, with child widgets. So if he somehow ended up adding widgets as children of the label they would pick up that color value. If you still used at least the QLabel selector, it would limit it to QLabels from here and belowVulgarity

© 2022 - 2024 — McMap. All rights reserved.