QML 状态:如果它不是其目标的子项,则不考虑

QML state: not taken into account if it's not a child of its target

假设我有一个矩形和一个状态块:

import QtQuick 2.0
import QtQuick.Window 2.11
import QtQuick.Controls 1.4



Window{
    id: main
    width: 800
    height: 800
    visible: true
    Item{

    Rectangle {
        id: rect
        width: 100
        height: 100
        color: "red"
        state: "ready"
    }

    states: [
            State {
                name: "ready"
                PropertyChanges {
                    target: rect
                    color: "lightblue"
                    opacity: 0.2
                }
            }
        ]
    }
}

为什么当我为我的Rectangle指定初始State时,它不受上述states的影响。请注意 states 块在 Rectangle 之外,我认为既然有目标,就没有必要将它放在 Rectangle 块内。

状态属于一个项目,因此当您指向矩形中的状态:"ready" 时,正在查看矩形的状态,而不是其他项目的状态。所以你有 2 个解决方案:

1.设置初始状态在Window:

Window{
    id: main
    width: 800
    height: 800
    visible: true
    Item{

        Rectangle {
            id: rect
            width: 100
            height: 100
            color: "red"
        }

        state: "ready"
        states: [
            State {
                name: "ready"
                PropertyChanges {
                    target: rect
                    color: "lightblue"
                    opacity: 0.2
                }
            }
        ]
    }
}

2.将状态移动到矩形作为它们的状态。

Window{
    id: main
    width: 800
    height: 800
    visible: true
    Item{

        Rectangle {
            id: rect
            width: 100
            height: 100
            color: "red"
            state: "ready"

            states: [
                State {
                    name: "ready"
                    PropertyChanges {
                        target: rect
                        color: "lightblue"
                        opacity: 0.2
                    }
                }
            ]
        }
    }  
}

如果你想从另一个 Item 分配初始状态,你必须使用对项目的引用,在下面的例子中,状态属于 id: it 的 Item 然后我们在 Rectangle 完成它的时候建立它建设:

Window{
    id: main
    width: 800
    height: 800
    visible: true
    Item{
        id: it
        Rectangle {
            id: rect
            width: 100
            height: 100
            color: "red"
            Component.onCompleted: it.state = "ready"
        }
        states: [
            State {
                name: "ready"
                PropertyChanges {
                    target: rect
                    color: "lightblue"
                    opacity: 0.2
                }
            }
        ]
    }
}