Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically update a rectangle's gradient?

Tags:

qt

qml

I have this:

    Rectangle{
    id:testrect

    property color gradcolor:"#8C8F8C"
    gradient:
        Gradient {
        GradientStop { position: 0.0; color: gradcolor }
        GradientStop { position: 0.17; color: "#6A6D6A" }
        GradientStop { position: 0.77; color: gradcolor }
        GradientStop { position: 1.0; color: "#6A6D6A" }
        }

In a child MouseArea, I want to do this:

         onEntered: {
            testrect.gradcolor="white"
            parent.border.color = Qt.lighter("#6A6D6A")

The border color is changing as desired, but the gradient colors are not. Is it because the gradient is not pulling from the gradcolor property in real time? What is the best way to approach this?

like image 983
johnbakers Avatar asked Mar 11 '26 06:03

johnbakers


1 Answers

The issue seems to be that your Gradient element is not linked to gradcolor if you don't indicate which element contains the property. This works for me:

Rectangle{
    id:testrect
    width: 200
    height: 200
    property color gradcolor: "green"
    gradient: Gradient {
        GradientStop { position: 0.0; color: testrect.gradcolor }
        GradientStop { position: 0.17; color: "#6A6D6A" }
        GradientStop { position: 0.77; color: testrect.gradcolor }
        GradientStop { position: 1.0; color: "#6A6D6A" }
    }

    MouseArea {
        anchors.fill:parent
        hoverEnabled: true  // Mandatory for hover events to work
        onEntered: {
            testrect.gradcolor = "red";
        }
        onExited: {
            testrect.gradcolor = "blue";
        }
    }
}

More information on QML scope can be found here

like image 95
koopajah Avatar answered Mar 15 '26 04:03

koopajah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!