Stefan Monov
Stefan Monov

Reputation: 11732

Qt Quick: Code redundancy when creating Transition

My code:

states: [
    State {
        name: "pressed"; when: mouseArea.pressed
        PropertyChanges {
            target: foo
            prop1: 10
            prop2: 10
            prop3: 10
        }
    },
    State {
        name: "notPressed"; when: !mouseArea.pressed
        PropertyChanges {
            target: foo
            prop1: 1
            prop2: 1
            prop3: 1
        }
    }
]
transitions: [
    Transition {
        to: "*"
        NumberAnimation {
            target: foo
            properties: "prop1,prop2,prop3"
            duration: 1000
        }
    }
]

This works, but requires me to redundantly specify properties: "prop1,prop2,prop3" when the properties to change are already specified in the PropertyChanges elements. Also, I need to redundantly specify target: foo in NumberAnimation when it's already specified in the PropertyChanges elements.

Can this redundancy be avoided? If not, why not?

Upvotes: 0

Views: 47

Answers (2)

GrecKo
GrecKo

Reputation: 7150

As @ddriver said, this is needed to have a fine control of what's animated during state changes.

However here if all your properties are changed to the same value like in your example, you could refactor that and bind them to a common property. Like so :

property int bar: mouseArea.pressed ? 10 : 1
prop1: bar
prop2: bar
prop3: bar

states: [
    State {
        name: "pressed"; when: mouseArea.pressed
        PropertyChanges {
            target: foo
            bar: 10
        }
    },
    State {
        name: "notPressed"; when: !mouseArea.pressed
        PropertyChanges {
            target: foo
            bar: 1
        }
    }
]
transitions: [
    Transition {
        to: "*"
        NumberAnimation {
            target: foo
            property: "bar"
            duration: 1000
        }
    }
]

Alternatively if your transition is symmetric (using the same animation going from state A -> state B and going from B -> A), you could use a Behavior to simplify your code :

property int bar: mouseArea.pressed ? 10 : 1
prop1: bar
prop2: bar
prop3: bar

Behavior on bar {
    NumberAnimation { duration: 1000 }
}

Upvotes: 2

dtech
dtech

Reputation: 49289

A property change does not necessary mean it will be animated. And it is not necessary that all property changes will have the same animation either.

I don't see a redundancy here, if the behavior you want was default you wouldn't be able to have fine grained control over what happens. You will be stuck with the same behavior for all property changes, which might suit your particular need, but will actually be quite problematic in all other scenarios.

Upvotes: 4

Related Questions