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

问题描述 投票:0回答:1

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

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
                }
            }
        ]
    }
}

为什么当我为我的State指定一个初始Rectangle时,它不受上述states的影响。请注意,states区块在Rectangle之外,我假设因为有一个目标,所以没有必要把它放在Rectangle区块内。

qt qml qtquick2
1个回答
1
投票

状态属于一个项目,因此当您指向状态时: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.将状态移动到Rectangle作为其状态。

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
                }
            }
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.