PyQt为特定元素赋予颜色

Joh*_*nna 12 python pyqt pyqt4 qlabel qtstylesheets

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

我尝试的代码如下:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet("QLabel#nom_plan_label {color: yellow}")
Run Code Online (Sandbox Code Playgroud)

任何提示都将不胜感激

ekh*_*oro 24

您正在使用的样式表语法有一些问题.

首先,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}')
Run Code Online (Sandbox Code Playgroud)

或者,更简单地说:

nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet('color: yellow')
Run Code Online (Sandbox Code Playgroud)