4

I want to intercept the QPaintEvent on a QSlider and draw it. But I can not find the details on the geometry of the thing. I can know the rect() of the whole widget but how can you tell the position of first tickmark or the last one in the widget's rectangle? (there's a margin at left and right of the tracking channel). Or the rectangle of the "handle"?

tru7
  • 6,348
  • 5
  • 35
  • 59

3 Answers3

9

Here's a way using QStyleOptionSlider and QStyle:

QStyleOptionSlider opt;
slider->initStyleOption(&opt);
    
QStyle *styl=style();
Rect rectHandle=styl->subControlRect(QStyle::CC_Slider, 
                                     &opt, 
                                     QStyle::SC_SliderHandle, 
                                     NULL);
Rect rectGroove=styl->subControlRect(QStyle::CC_Slider, 
                                     &opt, 
                                     QStyle::SC_SliderGroove, 
                                     NULL);

// width in an horizontal slider of the groove (width of widget - margins)    
int avl=styl->pixelMetric(QStyle::PM_SliderSpaceAvailable, &opt, this); 
tru7
  • 6,348
  • 5
  • 35
  • 59
1

It might be enough to write a custom style sheet.

Here is an example for QSlider:

QSlider::groove:horizontal {
    border: 1px solid #999999;
    height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);
    margin: 2px 0;
}
    
QSlider::handle:horizontal {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);
    border: 1px solid #5c5c5c;
    width: 18px;
    margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
    border-radius: 3px;
}
Ruslan F.
  • 5,498
  • 3
  • 23
  • 42
  • Thanks, in fact it's easier for me to intercept the QPaint and additionally I wanted to dinamically draw it, when other values change redraw the background (the context is a color defninition HSL, each slider paints the available gamut depending on the other values) – tru7 Aug 05 '13 at 10:48
1

Have you considered using setStyleSheet instead ? If you really want to draw it yourself, you can have a look at how it's done in Qt source code: qt/src/gui/widgets/qslider.cpp

Sylvain V
  • 194
  • 1
  • 7