morte
morte

Reputation: 361

Qml Item states: previous state

I want to declare states that take into account the previous state. Is it possible to use the previous state name in PropertyChanges/StateChangeScript?

Item {
    states: [ 
        State {
            name: "s1" 

            StateChangeScript { 
                if (previous_state == "s2") 
                    doSomething();
                else 
                   doSomethingElse();
            }
        }, 
        State {
            name: "s2"
        },
        State {
            name: "s3"
        }
    ]
}

Upvotes: 4

Views: 1372

Answers (2)

Paul Killam
Paul Killam

Reputation: 21

In researching this problem, I've found another solution which may benefit the wayward googler stumbling upon this thread.

The other stated answer requires you to define a transition for every state you have, which becomes inconvenient for larger programs with many states.

Also, at least currently in qml,

onStateChanged: previousState = state

results in previousState holding the current state, rather than the previous one.

so, my solution:

//within main:
property string previous_state: ""
property string current_state: "default_state"

Transition{
  PropertyAction {target: main; property: "previous_state"; value: main.current_state}
  PropertyAction {target: main; property: "current_state"; value: main.state}
}

previous_state will always hold the previous state, and does not require you to define a new transition for every state you have.

The one caveat is you have to set current_state to whatever the default state is, so previous_state is correct after the first, rather than the second transition.

Upvotes: 2

iBelieve
iBelieve

Reputation: 1544

As @folibis suggested, you could use a property to save the previous state. There's also another way to do it using ScriptAction:

Item {
    states: [
        State {
            name: "s1"
        },
        State {
            name: "s2"
        },
        State {
            name: "s3"
        }
    ]

    transitions: [
        Transition {
            from: "s2"; to: "s1"

            ScriptAction {
                script: doSomething()
            }
        },
        Transition {
            from: "s3"; to: "s1"

            ScriptAction {
                script: doSomethingElse()
            }
        }
    ]
}

Upvotes: 1

Related Questions