qtslidercustom-draw

Custom drawing of a QSlider (Qt)


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"?


Solution

  • 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);