Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 setting 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; }
like image 619
Anna B Avatar asked Jan 04 '11 18:01

Anna B


1 Answers

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
like image 92
Anna B Avatar answered Oct 07 '22 11:10

Anna B