QLabel: set color of text and background

396,376

Solution 1

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.

Solution 2

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

Solution 3

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,

Solution 4

The ONLY thing that worked for me was html.

And I found it to be the far easier to do than any of the programmatic approaches.

The following code changes the text color based on a parameter passed by a caller.

enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
    QTextCursor cursor = ui->messages->textCursor();
    QString alertHtml  = "<font color=\"DeepPink\">";
    QString notifyHtml = "<font color=\"Lime\">";
    QString infoHtml   = "<font color=\"Aqua\">";
    QString endHtml    = "</font><br>";
    switch(level)
    {
        case msg_alert:  line = alertHtml % line; break;
        case msg_notify: line = notifyHtml % line; break;
        case msg_info:   line = infoHtml % line; break;
        default:         line = infoHtml % line; break;
    }
    line = line % endHtml;
    ui->messages->insertHtml(line);
    cursor.movePosition(QTextCursor::End);
    ui->messages->setTextCursor(cursor);
}

Solution 5

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.

Share:
396,376

Related videos on Youtube

Regof
Author by

Regof

Updated on February 02, 2022

Comments

  • Regof
    Regof 11 months

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

  • alisami over 12 years
    In designer, click "Form->View Code" to see the generated code.
  • Dave Johansen
    Dave Johansen over 10 years
    I have been using the setStyleSheet() method and at least in Qt 4.4 it ends up calling connect and in the Style Sheet stuff and causing an increase in memory use.
  • Dave Johansen
    Dave Johansen over 10 years
    I opened a bug report about the increased memory usage which can be found here.
  • peterh
    peterh about 7 years
    Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected.
  • i know nothing
    i know nothing almost 7 years
    Same here, neither QPalette nor stylesheets worked for me, very annoying!
  • rbaleksandar
    rbaleksandar almost 7 years
    I prefer this way since it also allows you to put some other fancy stuff inside the <font/> tag (and is something more familiar to HTML people :D) and not just a colour hence it gives you greater flexibility.
  • Eliyahu Skoczylas
    Eliyahu Skoczylas over 6 years
    This is the most important single element of ANY approach (except styleSheets.)
  • Victor Polevoy
    Victor Polevoy over 6 years
    @iknownothing stylesheets work through QPalette... Everything uses QPalette.
  • BSD
    BSD over 4 years
    Thank you for pointing out that the autoFillBackground is a key issue here. The accepted answer above does not work without that setting.
  • Scott Aron Bloom
    Scott Aron Bloom over 4 years
    While this code works, there are some definate optimizations <code> QColor color = QColorDialog::getColor( QColor( Qt::white ), this, tr( "Select Color" ); // use the static function to select the color, the initial value is white </br> ui->label->setStyleSheet( QString( "QLabel { background-color :%1; color : blue; }""+colcode+" ; color : blue; }" ).arg( color.name() ); // color.name returns a #RRGGBB formatted string </code>
  • Paulo Carvalho
    Paulo Carvalho almost 4 years
    The color attribute is ineffective. Only via HTML <font color="#FFFFFF">...</font> I was able to set font color (to white in this case.
  • AstroFloyd
    AstroFloyd over 3 years
    Is there a way to specify the default (text) colour of the user's desktop? Using color: ; as a 'reset' seems to do it, but is this good practice, or is there a better method?

Related