QLabel: set color of text and background
The best and recommended way is to use Qt Style Sheet. Docs: Qt 5 Style Sheet, Qt 6 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.
I add this answer because I think it could be useful to anybody.
I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.
As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
where color
is an RGBA color.
So, my dirty solution was to extend QLabel
and override paintEvent()
method filling its bounding rect.
Today, I've open up the qt-assistant
and read the style reference properties list. Affortunately, it has an example that states the following:
QLineEdit { background-color: rgb(255, 0, 0) }
Thats open up my mind in doing something like the code below, as an example:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
Note that setAutoFillBackground()
set in False
will not make it work.
Regards,
You can use QPalette, however you must set setAutoFillBackground(true);
to enable background color
QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);
sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");
It works fine on Windows and Ubuntu, I haven't played with any other OS.
Note: Please see QPalette, color role section for more details