tags:

views:

1083

answers:

3

How do I set color of text and background of a QLabel?

+2  A: 

There are two ways to do this. I think the way you are looking for is done through style sheets, which are almost identical to the CSS variety, although much more well-specified (and supported). If you are looking to effect the style of the entire application, you can set the brushes of the QPalette, but that is generally overkill.

Travis Gockel
thanks, and without css? just color of the label text?
Regof
I believe that functionality was removed in the transition from Qt 3 to Qt 4. It enabled them to get more consistent behavior more efficiently.
Travis Gockel
+2  A: 

The best way to set any feature regarding the colors of any widget is to use QPalette.

And the easiest way to find what you are looking for is to open Qt Designer and set the palette of a QLabel and check the generated code.

alisami
How do I see the generated code?
Regof
In designer, click "Form->View Code" to see the generated code.
alisami
+4  A: 

The best and recommanded way is to use Qt Style Sheet.

To change the text color and background color of a QLabel, here is what I would do :

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

You could also avoid using Qt Style Sheets and change the QPalette colors of your QLabel, but you might get different results on different platforms and/or styles.

As Qt documentation states :

Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.

But you could do something like this :

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.

Jérôme