2
votes

I have a Slider. value reads from my persistent value and onValueChanged writes to it. However, setting minimumValue to, say 1, calls onValueChanged before the initial access of my value. This causes my persistent value to be overwritten to 1 always.

eg

Slider
{
    stepSize: 1
    minimumValue: 1  // this happens before `value` regarless of order here
    maximumValue: 5
    value: myPersistentValue
    onValueChanged:
    {
        // gets called *before* myPersistentValue is accessed and overwrites it!
        myPersistentValue = value
    }
}

Is there some way to prevent this or test for readiness somehow?

thanks.

1
This is a dependency loop, and is invalid. You must do something else, this won't ever work. It only happens to work because the QML engine breaks dependency loops for you as a last resort to prevent a crash/frozen GUI. - Kuba hasn't forgotten Monica

1 Answers

1
votes

I think the best way of solving this is using a bool to control whether the Slider is completed or not so myPersistentValue will be changed only when Slider is already completed.

Something like this:

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    id: rootWindow
    objectName: "window"
    visible: true
    width: 200
    height: 200

    property int myPersistentValue: 5

    Slider
    {
        id: mySlider
        stepSize: 1
        minimumValue: 1
        maximumValue: 5
        value: myPersistentValue

        property bool completed: false

        onValueChanged:
        {
            console.log("slider - onValueChanged: " + myPersistentValue +
                        " value: " + value )

            if (completed) {
                console.log("slider - onValueChanged & completed: " + myPersistentValue +
                            " value: " + value )
                myPersistentValue = value
            }
        }

        Component.onCompleted: {
           console.log("Slider completed!")
           completed = true
        }
    }


    Button
    {
        y: 50
        text: "click me!"
        onClicked: {
            myPersistentValue = myPersistentValue - 1
            console.log("button - onClicked: " + myPersistentValue)
        }
    }
}

I would be great if QML standard components had this information, but I'm afraid not.

By the way, surprisingly, if you set minimumValue less than or equal to 0, the behaviour is different. During the initialization, onValueChanged is only called once and value is equal to myPersistentValue.