PyQt为特定元素设置颜色
这可能是个简单的问题,但我想给我应用程序中的一个特定 QLabel 设置颜色,但它没有成功。
我尝试的代码如下:
nom_plan_label = QtGui.QLabel()
nom_plan_label.setText(nom_plan_vignette)
nom_plan_label.setStyleSheet("QLabel#nom_plan_label {color: yellow}")
任何提示都会很感激。
1 个回答
33
你使用的样式表语法有几个问题。
首先,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')