自定义Qt类的CSS选择器

gas*_*ard 10 css qt qt4 css-selectors

我创建了QWidget的"Slider"子类,并希望能够使用Qt的样式表来设置它.有没有办法将窗口小部件声明为Qt应用程序,以便应用程序样式表中的此设置应用于所有滑块?

Slider { background-color:blue; }
Run Code Online (Sandbox Code Playgroud)

或者,如果这不可能,我可以使用这样的类吗?

QWidget.slider { background-color:blue; }
Run Code Online (Sandbox Code Playgroud)

gas*_*ard 17

小部件具有可通过元对象访问的"className()"方法.在我的情况下,这是:

slider.metaObject()->className();
// ==> mimas::Slider
Run Code Online (Sandbox Code Playgroud)

由于"Slider"类位于命名空间中,因此必须使用完全限定名称进行样式化(将"::"替换为" - "):

mimas--Slider { background-color:blue; }
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是定义一个类属性并将其与前导点一起使用:

.slider { background-color:blue; }
Run Code Online (Sandbox Code Playgroud)

C++ Slider类:

Q_PROPERTY(QString class READ cssClass)
...
QString cssClass() { return QString("slider"); }
Run Code Online (Sandbox Code Playgroud)

在这个主题上,要使用CSS中定义的颜色和样式绘制滑块,这就是你得到它们的方式(链接文本):

// 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
Run Code Online (Sandbox Code Playgroud)

最后,关于CSS的QPalette值的注释:

color                      = QPalette::WindowText
background                 = QPalette::Window
alternate-background-color = QPalette::AlternateBase
selection-background-color = QPalette::Highlighted
selection-color            = QPalette::HighlightedText
Run Code Online (Sandbox Code Playgroud)