How do I change the color of a label text?

  • One way is to do it like this:

    ui->label->setText("<font color='red'>text</font>");

    But I want the user to be able to set the color. I have the color in QColor color, but how do I change the label's text color to that? Doesn't obviously work like this:

    QColor color = "orange";
    ui->label->setText("<font color='color'>text</font>");

    So how can I do it?

  • Hi,
    you can do that with styleSheet:

    ui->label->setStyleSheet("{color: #C0BBFE}");

  • Hi, you can change the color palette of the QLabel and set the WindowText (that will change the text color).
    in the UI editor click on "Change Palette" and play around with that, if you need to do that in c++ you can change the color in the UI file and copy the generated c++ code from the *_ui.h file (or do it yourself). If you want to reuse your QColor and not some CSS styles.

  • That doesn't exactly solve the problem. The QColor color = "orange" was just thrown there as an example. What I have is closer to something like this:

    QColor color = QColorDialog::getColor(Qt::white, this);

    So how do I set the color of the font to match that color?

  • Moderators

    Yet another way:
    @QColor color = ...;
    QString format("<font color="%1">%2</font>");
    label->setText(format.arg(, text));

  • @buon43: you can use the style sheet like Clochydd said or change the palette color like I said, so what is your problem with that? Both ways are not related to the text in the label so you can change the label color and text independently.

    maybe you need an example, I told you how you can see the c++ code and generate it yourself, but well here you go:
    QColor color = QColorDialog::getColor(Qt::white, this);
    QPalette palette = ui->label->palette();
    palette.setColor(QPalette::WindowText, color);
    maybe that's a little bit more code but you can directly use your QColor.

  • Thanks, that worked. Certainly more work than I thought for setting up a color like that.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.