开发者

CSS selector for custom Qt class

I created a "Slider" subclass of QWidget and would like to be able to style it with Qt's stylesheets. Is there a way to declare the widget to Qt application so that this setti开发者_如何学Gong in the application stylesheet is applied to all sliders ?

Slider { background-color:blue; }

Or if this is not possible, can I use a class like this ?

QWidget.slider { background-color:blue; }


The widgets have a "className()" method that is accessible via the meta object. In my case this is:

slider.metaObject()->className();
// ==> mimas::Slider

Since the "Slider" class is in a namespace, you have to use the fully qualified name for styling (replacing '::' with '--'):

mimas--Slider { background-color:blue; }

Another solution is to define a class property and use it with a leading dot:

.slider { background-color:blue; }

C++ Slider class:

Q_PROPERTY(QString class READ cssClass)
...
QString cssClass() { return QString("slider"); }

While on the subject, to draw the slider with colors and styles defined in CSS, this is how you get them (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

And finally, a note on QPalette values from CSS:

color                      = QPalette::WindowText
background                 = QPalette::Window
alternate-background-color = QPalette::AlternateBase
selection-background-color = QPalette::Highlighted
selection-color            = QPalette::HighlightedText
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜