Search code examples
qtsliderqmlqtquick2qtquickcontrols

Qml slider style, assigning different groove color before and after the slider's handle


So I wanted to create a slider style, similar to the default one, and also more matching to my applications style, but I found it hard to assign a different color before and after the slider's handle.

Here's a simplified version of my code, without gradients, anchor points and other properties:

Slider{
            id: widthSlider
            style: SliderStyle {
                    groove: Rectangle {
                        height: widthSlider.height*0.17
                        width: widthSlider.width
                        color: "black"
                        radius: 8
                    }
                    handle: Rectangle {
                        color: "grey"
                    }
                }
        }

I tried a rough workaround, to put two rectangles in the slider, anchored to the handle position like this:

Slider{
            id: widthSlider
            Rectangle {
                anchors.left: widthSlider.left
                anchors.right: widthSlider.__handlePos
                color: "black"
            }
            Rectangle {
                anchors.left: widthSlider.__handlePos
                anchors.right: widthSlider.right
                color: "white"
            }
     ...
}

but I cannot anchor to the handle's position since it's just a double(I get the error: Unable to assign double to QQuickAnchorLine).

Does anyone have an idea of how I could do this in Qml?


Solution

  • Something like this?

    Slider {
        anchors.centerIn: parent
        value: 0.5
        width: 400
        style: SliderStyle {
            groove: Item {
                implicitHeight: 10
                LinearGradient {
                    anchors.fill: parent
                    start: Qt.point(0, control.height / 2)
                    end: Qt.point(control.width, control.height / 2)
                    gradient: Gradient {
                        GradientStop { position: 0.0; color: "orange" }
                        GradientStop { position: control.value; color: "brown" }
                        GradientStop { position: 1.0; color: "orange" }
                    }
                }
            }
        }
    }
    

    Or:

    Slider {
        anchors.centerIn: parent
        value: 0.5
        width: 400
        style: SliderStyle {
            groove: Rectangle {
                implicitHeight: 10
                color: "lightgrey"
                border {
                    color: "#999"
                    width: 1
                }
                Rectangle {
                    implicitHeight: 10
                    color: "orange"
                    implicitWidth: control.value * parent.width
                    border {
                        color: "#999"
                        width: 1
                    }
                }
            }
        }
    }