自定义绘制QSlider(Qt)

4

我希望能够拦截QSlider上的QPaintEvent并进行绘制。但是我找不到关于其几何细节的详细信息。我可以了解整个小部件的rect(),但是如何确定小部件矩形内第一个刻度线或最后一个刻度线的位置?(在跟踪通道的左右两侧有一个边距)。或者“手柄”的矩形?

3个回答

9
这里有一种使用QStyleOptionSliderQStyle的方法:
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); 

1
可能只需要编写一个自定义样式表就足够了。
这里是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;
}

谢谢,事实上对我来说拦截QPaint更容易,此外我想动态绘制它,当其他值改变时重新绘制背景(上下文是颜色定义HSL,每个滑块根据其他值绘制可用的色域)。 - tru7

1

你是否考虑使用setStyleSheet呢?如果你真的想自己绘制,可以查看Qt源代码中的实现方式:qt/src/gui/widgets/qslider.cpp


感谢您提供源代码的提示,通过一些测试,我找到了所需的所有内容。 - tru7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接