سؤال

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

هل كانت مفيدة؟

المحلول

Thanks for the hints in the replies. After some investigation this seems to work. For the case if it is of use to someone:

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

int avl=styl->pixelMetric(QStyle::PM_SliderSpaceAvailable, &opt, this); // width in an horizontal slider of the groove (width of widget - margins)

نصائح أخرى

Are you shure that you want to reimplement a paint event?
May be it will be enough to wryte a custom style sheet?
Here is an example for qslider from doks:

 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;
 }

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top