PyQt为特定元素赋予颜色

问题描述 投票:12回答:1

这可能是一个简单的问题,但我试图在我的应用程序中为特定的QLabel赋予颜色,但它不起作用。

我尝试的代码如下:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet("QLabel#nom_plan_label {color: yellow}")

任何提示都将不胜感激

python pyqt pyqt4 qtstylesheets qlabel
1个回答
23
投票

你正在使用的stylesheet syntax有一些问题。

首先,ID选择器(即#nom_plan_label)必须引用小部件的objectName

其次,只有在将样式表应用于祖先窗口小部件并且您希望某些样式规则级联到特定的后代窗口小部件时,才需要使用选择器。如果您将样式表直接应用于一个窗口小部件,则可以省略选择器(和大括号)。

鉴于以上两点,您的示例代码将成为:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setObjectName('nom_plan_label')
nom_plan_label.setStyleSheet('QLabel#nom_plan_label {color: yellow}')

或者,更简单地说:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet('color: yellow')
© www.soinside.com 2019 - 2024. All rights reserved.