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

2024-04-23 06:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文本颜色背景qlabel
3条回答

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

在我的绘画应用程序中,我进入了为彩色显示标签设置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) }

以下面的代码为例,这样做可以开阔我的思路:

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()将无法使其工作。

谨致问候

您可以使用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,color role部分

最好和推荐的方法是使用Qt Style Sheet

要更改QLabel的文本颜色和背景颜色,我将执行以下操作:

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

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

正如Qt文档所述:

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.

但你可以这样做:

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

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

相关问题 更多 >