A.J
A.J

Reputation: 348

Doing somethings when state be replaced

I wants to change some property or run scripts when particular state exits.

In formal, I will use a variable to save the previous state. When the state changing, checking previous state and determine whether run scripts. But code will more redundant as number of state increase. How can I simplify that?

e.g. How to simplify following code?

Item {
    property var work
    property var preState
    states: [
        State {
            name: "state1";
            ...
        },
        State {
            name: "state2";
            ...
        }
        ...
        State {
            name: "stateN";
            ...
        }
    ]
    onStateChanged: {
        if (preState == "state1") {
            ...
        } else if (preState == "state2") {
            ...
        } else if (preState == "stateN") {
            ...
        }
    }
    ...
}

Upvotes: 0

Views: 563

Answers (2)

derM
derM

Reputation: 13691

If you want to use it as declarative as possible, you will avoid using scripts on a state change. Instead you declaratively state, what shall change when a new State is entered.

For this you can provide a list of PropertyChanges elements.

You can also change anchors and the parent parent with specialized Changes. If you need to run a script, the right way is to use a StateChangeScript element.

To animate the changes, add Transitions.

Here you can find more information on the usage of the States

The Syntax is pretty easy:

State {
    name: 'myState1'
    PropertyChanges { target: root; color: 'green' }
    AnchorChanges { target: child; anchors.top: root.bottom }
    // ... some more if necessary ...
}

The good thing about using the Changes is, that the result is automatically a binding, rather than a assignment what it would be, if you would set it in a script. (without Qt.binding(...))

Upvotes: 1

Bibin
Bibin

Reputation: 463

You can use onStateChanged signal for that

Item {
    id:stateTest
    property var work
    property var prevState
    states: [
        State {
            name: "state1";

        },
        State {
            name: "state2";

        },

        State {
            name: "stateN";

        }
    ]

    onStateChanged: {

        work="whatever"

       prevState=state
    }

    Component.onCompleted: prevState=state
}

Upvotes: 0

Related Questions