如何设置QLabel的文本和背景颜色?


关于任何小部件的颜色设置任何特性的最佳方法是使用QPalette。

找到你要找的最简单的方法是打开Qt Designer,设置QLabel的面板,并检查生成的代码。


最好的和推荐的方法是使用Qt样式表。文档:Qt 5样式表,Qt 6样式表。

要改变一个QLabel的文本颜色和背景颜色,下面是我要做的:

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

您也可以避免使用Qt样式表,并更改QLabel的QPalette颜色,但在不同的平台和/或样式上可能会得到不同的结果。

正如Qt文档所述:

使用QPalette并不能保证适用于所有样式,因为样式作者受到不同平台的指导方针和本机主题引擎的限制。

但是你可以这样做:

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

但正如我所说,我强烈建议不要使用调色板,而是使用Qt样式表。


我加上这个答案是因为我认为它对任何人都有用。

我开始在我的绘画应用程序中为颜色显示标签设置RGBA颜色(即带有Alpha值的RGB颜色)的问题。

当我遇到第一个答案时,我无法设置RGBA颜色。我也尝试过以下方法:

myLabel。setStyleSheet("QLabel {background-color: %s"%color.name())

其中颜色是RGBA颜色。

因此,我的肮脏解决方案是扩展QLabel并覆盖paintEvent()方法填充其边界矩形。

今天,我打开了qt-assistant并阅读了样式引用属性列表。幸运的是,它有一个例子,说明如下:

QLineEdit {background-color: rgb(255,0,0)}

这打开了我的思路,在做一些像下面的代码,作为一个例子:

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

注意在False中设置的setAutoFillBackground()不会使它工作。

问候,


对我来说唯一有用的就是html。

我发现这比任何程序化的方法都要容易得多。

下面的代码根据调用者传递的参数更改文本颜色。

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

你可以使用QPalette,但是你必须设置setAutoFillBackground(true);启用背景色

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

它在Windows和Ubuntu上运行良好,我还没玩过其他任何操作系统。

注:详情请参阅QPalette,颜色角色部分


这台工作得很完美

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

方法返回所选颜色。 您可以使用样式表更改标签颜色