ChatGPT解决这个技术问题 Extra ChatGPT

QLabel: set color of text and background

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


J
Joundill

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 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.
I opened a bug report about the increased memory usage which can be found here.
The color attribute is ineffective. Only via HTML <font color="#FFFFFF">...</font> I was able to set font color (to white in this case.
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?
L
Linville

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


This is the most important single element of ANY approach (except styleSheets.)
Thank you for pointing out that the autoFillBackground is a key issue here. The accepted answer above does not work without that setting.
C
Community

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,


p
paie

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

Same here, neither QPalette nor stylesheets worked for me, very annoying!
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.
@iknownothing stylesheets work through QPalette... Everything uses QPalette.
L
Linville

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.


In designer, click "Form->View Code" to see the generated code.
z
zubergu

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet


Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected.
While this code works, there are some definate optimizations QColor color = QColorDialog::getColor( QColor( Qt::white ), this, tr( "Select Color" ); // use the static function to select the color, the initial value is white
ui->label->setStyleSheet( QString( "QLabel { background-color :%1; color : blue; }""+colcode+" ; color : blue; }" ).arg( color.name() ); // color.name returns a #RRGGBB formatted string

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now