首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >QLabel:设置文本和背景的颜色

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

Stack Overflow用户
提问于 2010-05-01 19:57:30
回答 5查看 388.4K关注 0票数 202

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

EN

回答 5

Stack Overflow用户

发布于 2012-07-20 07:41:27

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

代码语言:javascript
复制
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,颜色角色部分

票数 52
EN

Stack Overflow用户

发布于 2011-07-30 00:59:18

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

我遇到了在绘画应用程序中为颜色显示标签设置RGBA颜色(即具有Alpha值的透明度的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) }

以下面的代码为例,这打开了我的思路:

代码语言:javascript
复制
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()不会使其工作。

致以敬意,

票数 24
EN

Stack Overflow用户

发布于 2011-08-04 07:03:26

唯一对我有效的就是html。

我发现它比任何一种编程方法都要容易得多。

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

代码语言:javascript
复制
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);
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2749798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档