QLabel:设置文本和背景的颜色 [英] QLabel: set color of text and background

查看:51
本文介绍了QLabel:设置文本和背景的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

最好和推荐的方法是使用 Qt 样式表.

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

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

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

正如 Qt 文档所述:

<块引用>

不能保证使用 QPalette 对所有样式都有效,因为样式作者受到不同平台指南和本机主题引擎的限制.

但是你可以这样做:

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

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

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

解决方案

The best and recommended way is to use Qt 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.

这篇关于QLabel:设置文本和背景的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆