c++ - 如何在 QSlider 的侧面添加图像

标签 c++ qt qtstylesheets qslider

我使用样式表重新设计并实现了 QSlider。

不过,我找不到如何在 slider 本身之前和之后(左或右、上或下)放置图像。

例如:

slider :

----00---------------

左图:

qqqqq

右图:

ddddd

结果:

qqqqq----00---------------ddddd

我目前正在使用 QHBoxLayout 并使用 QLabels 插入这些图像,但这似乎不是正确或最佳的方式。

我怎样才能正确添加这些图像?

谢谢!

最佳答案

您实际上可以仅使用样式表和 groove 子控件上的 border-image 属性来实现这一点。

例如像这样的边框图像:

Slider decoration image

为了更好地了解什么发生了什么,B 的宽度为 10 像素,间距为 2,A 的宽度为 12 像素。

QSlider::groove {      
   border-image: url(:/slider-decoration.png) 0 12 0 10;
   border-left: 10px solid transparent;
   border-right: 12px solid transparent;
}
QSlider::handle {
    width: 8px;
    background-color: green;
}

这给了你你所期望的:

resulting slider

不过,这个解决方案有一个小问题。鼠标忽略边框的存在,在 handle 位置和鼠标位置之间的两端附近有一个偏移量。 因此,为避免这种情况, handle 必须一直延伸到任一侧,但我们为其添加了一个透明边框,使其看起来就像停在图像边框之前:

QSlider::groove {      
   border-image: url(:/slider-decoration.png) 0 12 0 10;
   border-left: 10px;
   border-right: 12px;
}
QSlider::handle {
    width: 8px;
    /* add borders to the handle that will sit above the groove border */
    border-right: 10px solid transparent;
    border-left: 12px solid transparent;       

    /* negative margins to allow the handle borders 
       to go past the groove borders */
    margin-right: -10px;    
    margin-left: -12px;
    background-color: green;
    /* make the background color fill the content, not the border */
    background-clip: content;
}

关于c++ - 如何在 QSlider 的侧面添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085655/

相关文章:

c++ - 覆盖继承中的重载函数

c++ - C++构造函数抛出异常

c++ - 递归缺陷——这段代码哪里出错了?

c++ - 使用两个图像设计 QPushButton

python - PyQt 为特定元素赋予颜色

c++ - 找出字符串是否仅包含给定字符集的最佳方法/算法

c++ - 对 vtable 的 undefined reference 。试图编译一个 Qt 项目

android - 如何在 Debug模式下将 Qt Creator 中的 --android-platform 更改为不是 android--1?

c++ - 判断SQLite数据库是否被锁定

qt-designer - 标题在组框中的位置