[SOLVED] QLabel: set color of text and background


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


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);

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

Answered By – Jérôme

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *