19

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

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Johanna
  • 1,343
  • 4
  • 25
  • 44

1 Answers1

33

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')
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • 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 below – jdi Dec 20 '11 at 17:27