12

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; }
BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
Anna B
  • 5,491
  • 5
  • 37
  • 50
  • Have you tried id (i.e. #blah { ... }) or class (i.e. .schmarr { ... }) selectors? – DwB Jan 04 '11 at 18:32

1 Answers1

19

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
BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
Anna B
  • 5,491
  • 5
  • 37
  • 50
  • It works b/c the "class" property works similarly to the html class property. (Space-separated list of classes.) Also, if you came here wondering how to do that in Python/PyQt/PySide like me: You have to use `self.setProperty` since you can't call a variable `class`. – serg06 Mar 11 '21 at 21:15