Search code examples
qtuser-interfaceqmlqt-quickqtquickcontrols

Slider Style: Gradient along the width of the groove


I am trying to create a custom QML Slider style as follows:

SliderStyle {
    groove: Item {
        anchors.verticalCenter: parent.verticalCenter
        implicitWidth: 500
        implicitHeight: 10
        Rectangle {
            radius: height/2
            anchors.fill: parent
            border.width: 1
            border.color: "#888"
            gradient: Gradient {
                GradientStop { color: "#0A406E" ; position: 0 }
                GradientStop { color: "#FFA800" ; position: 1 }
            }
        }
    }
}

However, the gradient on the groove here is going from top to bottom rather than left to right. I tried swapping the width and height values and rotating the Rectangle by -90 degrees but then the slider was unresponsive. Also, I could never get the rotation to be done along the centre of the slider control, which made placement a bit problematic.

I was wondering if there is a way to achieve this left->right gradient flow.


Solution

  • Rectangle's property gradient allows for the construction of simple vertical gradients. For more complex gradients there are LinearGradient, RadialGradient and ConicalGradient types.

    For example, horizontal gradient:

    import QtGraphicalEffects 1.0
    
    SliderStyle {
        groove: Item {
            anchors.verticalCenter: parent.verticalCenter
            implicitWidth: 500
            implicitHeight: 10
            Rectangle {
                radius: height/2
                anchors.fill: parent
                border.width: 1
                border.color: "#888"
                layer.enabled: true
                layer.effect: LinearGradient {
                    start: Qt.point(0, 0)
                    end: Qt.point(500, 0)
                    gradient: Gradient {
                        GradientStop { position: 0.0; color: "#0A406E" }
                        GradientStop { position: 1.0; color: "#FFA800" }
                    }
                }
            }
        }
    }