QLabel:设置文本和背景的颜色

222

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

6个回答

325

最佳且推荐的方法是使用Qt样式表。文档:Qt 5 样式表Qt 6 样式表

要更改QLabel的文本颜色和背景颜色,我会这样做:

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

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

因为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样式表。


我一直在使用setStyleSheet()方法,至少在Qt 4.4中它最终会调用connect和Style Sheet相关的内容,导致内存使用增加。 - Dave Johansen
我提交了一个有关内存使用增加的错误报告,可以在这里找到。 - Dave Johansen
color 属性无效。只有通过 HTML <font color="#FFFFFF">...</font> 才能设置字体颜色(在这种情况下为白色)。 - Paulo Carvalho
有没有一种方法可以指定用户桌面的默认(文本)颜色?使用 color: ; 作为“重置”似乎可以做到这一点,但这是好的实践吗,还是有更好的方法? - AstroFloyd

58

您可以使用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的颜色角色部分。


这是任何方法中最重要的单个元素(除了样式表)。 - Eliyahu Skoczylas
5
感谢您指出autoFillBackground是一个关键问题。上面的已接受答案如果没有这个设置是无法工作的。 - BSD

28

我添加了这个答案,因为我认为它可能对任何人都有用。

我遇到了一个问题,即在我的绘画应用程序中设置RGBA颜色(即具有透明度的RGB颜色)。当我遇到第一个答案时,我无法设置RGBA颜色。我还尝试过像以下代码一样的东西:

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

其中color是一个RGBA颜色。

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

今天,我打开了qt-assistant并阅读了style reference properties list。幸运的是,它有一个示例,声明如下:

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

请注意,将setAutoFillBackground()设置为False不会使其起作用。
问候,

14

唯一对我有效的是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和样式表都没用,非常烦人! - i know nothing
我更喜欢这种方式,因为它还允许您在 <font/> 标签中放置其他一些花哨的东西(对于熟悉 HTML 的人来说更加熟悉:D),而不仅仅是颜色,因此它给您带来了更大的灵活性。 - rbaleksandar
@iknownothing 样式表通过 QPalette 工作... 所有东西都使用 QPalette。 - Victor Polevoy

13

设置任何小部件颜色方面的最佳方法是使用QPalette

查找您要查找的内容最简单的方法是打开Qt Designer,设置QLabel的调色板并检查生成的代码。


2
在设计器中,点击“窗体->查看代码”以查看生成的代码。 - alisami

7

这个运行得很完美

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() 方法返回所选颜色。您可以使用 stylesheet 更改标签颜色。


1
尽管代码受到赞赏,但它应该始终有相应的解释。这并不需要很长,但是这是期望的。 - peterh
虽然这段代码可以工作,但是有一些明显的优化。<code> QColor color = QColorDialog::getColor( QColor( Qt::white ), this, tr( "Select Color" ); // 使用静态函数选择颜色,初始值为白色 </br> ui->label->setStyleSheet( QString( "QLabel { background-color :%1; color : blue; }""+colcode+" ; color : blue; }" ).arg( color.name() ); // color.name 返回一个 #RRGGBB 格式的字符串 </code> - Scott Aron Bloom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接