Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qml Item states: previous state

Tags:

qt

qml

qtquick2

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"
        }
    ]
}
like image 987
morte Avatar asked Oct 19 '25 03:10

morte


2 Answers

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.

like image 65
Paul Killam Avatar answered Oct 21 '25 17:10

Paul Killam


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()
            }
        }
    ]
}
like image 27
iBelieve Avatar answered Oct 21 '25 18:10

iBelieve



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!