3
votes
  • I am designing a UI with Qt Creator 3.6.1
  • I am using Qt designer form.
  • I have a QWidget which contains 20 QLabels.
  • I want 10 of these QLabels to have a red background color
    and the other 10 to have a blue background color.
  • I want to use css for this purpose.

I found out that you can style all QLabels in parent widget css which will style all labels.

QLabel
{
    background-color: red
}

However in my case I want two classes of styles. Is there a way to do so by not styling each of the remaining 10 blue labels individually?

I know that I can style elements by name but that's a huge amount of effort.

1
Why not just change the palette for the labels? Call setAutoFillBackground(true) on the labels and set to a palette with the QPalette::Window role set. Use one palette for red, another for blue.anonymous

1 Answers

5
votes

If you want to use CSS class you have to set a class name to your QLabels:

QLabel* redLabel = new QLabel("red label");
QLabel* blueLabel = new QLabel("blue label");

redLabel->setProperty("class","my-1st-class");
blueLabel->setProperty("class","my-2nd-class");

Then use your class names in your CSS file :

.my-1st-class{
     background-color: red;
}

.my-2nd-class{
     background-color: blue;
}