继续上一篇,所有基于Item的组件都有一个state属性和一个默认状态。默认状态就是空字符串(“”),包含了项目的所有初始值。
import QtQuick 2.6
import QtQuick.Controls 1.5
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle {
id: myRect
width: 100; height: 100
color: "red"
MouseArea { id: mouseArea; anchors.fill: parent }
states: State {
name: "hidden"; when: mouseArea.pressed
PropertyChanges { target: myRect; opacity: 0 }
}
}
}
运行效果:
松开鼠标,红色矩形又显示出来。
通过when可以绑定一个状态,当when中的条件为true的时候切换状态,否则就恢复默认状态。
如果有一组状态需要和多个when进行绑定,可以用以下代码格式:
Item {
states: [
State { name: "state1"; when: sharedCondition },
State { name: "state2"; when: sharedCondition }
]
// ...
}
举例二:
import QtQuick 2.6
import QtQuick.Controls 1.5
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle {
id: myRect
width: 100; height: 100
color: "black"
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: myRect.state == 'clicked' ? myRect.state = "" : myRect.state = 'clicked';
}
states: [
State {
name: "clicked"
PropertyChanges { target: myRect; color: "red" }
}
]
}
}
运行效果:
初始的时候:
点击后:
松开鼠标,颜色不会变化,点击后又会进行颜色切换。这样就可以实现两种状态的切换。