假设我有一个矩形和一个状态块:
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
区块内。
状态属于一个项目,因此当您指向状态时: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
}
}
]
}
}