我创建了QWidget的“Slider”子类,并希望能够使用Qt的样式表来设置它。有没有办法将窗口小部件声明为Qt应用程序,以便应用程序样式表中的此设置应用于所有滑块?
Slider { background-color:blue; }
或者如果这不可能,我可以使用这样的课吗?
QWidget.slider { background-color:blue; }
答案 0 :(得分:17)
小部件有一个“className()”方法,可以通过元对象访问。在我的情况下,这是:
slider.metaObject()->className();
// ==> mimas::Slider
由于“Slider”类位于命名空间中,因此您必须使用完全限定名称进行样式设置(将“::”替换为“ - ”):
mimas--Slider { background-color:blue; }
另一个解决方案是定义一个类属性并将其与前导点一起使用:
.slider { background-color:blue; }
C ++ Slider类:
Q_PROPERTY(QString class READ cssClass)
...
QString cssClass() { return QString("slider"); }
在这个主题上,要使用CSS中定义的颜色和样式绘制滑块,这就是你得到它们的方式(link text):
// background-color:
palette.color(QPalette::Window)
// color:
palette.color(QPalette::WindowText)
// border-width:
// not possible (too bad...). To make it work, you would need to copy paste
// some headers defined in qstylesheetstyle.cpp for QRenderRule class inside,
// get the private headers for QStyleSheetStyle and change them so you can call
// renderRule and then you could use the rule to get the width borders. But your
// code won't link because the symbol for QStyleSheetStyle are local in QtGui.
// The official and supported solution is to use property:
// qproperty-border:
border_width_ // or whatever stores the Q_PROPERTY border
最后,关于CSS的QPalette值的注释:
color = QPalette::WindowText
background = QPalette::Window
alternate-background-color = QPalette::AlternateBase
selection-background-color = QPalette::Highlighted
selection-color = QPalette::HighlightedText