- Connection 可以连接一个目标元素任意数量的信号
- 通过改变 target 可以在不同的时间监控不同的元素
- 注意当多个信号被处理调用所有操作时,执行的顺序是未定义的
- 当创建一个连接元素(Connection element)未指定目标属性时,默认的属性是父对象
- 这意味着需要显式的设置NULL来避免捕获来自父对象的信号,直到 target 被设置
说白了,就是 Connection 的用法!
代码:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 600
height: 400
title: qsTr("Hello World")
Item {
anchors.fill: parent
Rectangle {
id: container
anchors.fill: parent
color: "white"
Column {
anchors.top: parent.top
anchors.left: parent.left
spacing: 20
// 鼠标点击之后赋值 container.state
Rectangle {
width: 290
height: 50
color: "lightGray"
MouseArea {
anchors.fill: parent
//
onClicked: container.state = "left"
}
Text {
anchors.centerIn: parent
font.pixelSize: 30
text: container.state==="left"?"Active":"inactive";
}
}
// 鼠标点击之后触发动画
Rectangle {
id: leftRectangle
width: 290
height: 200
color: "green"
MouseArea {
id: leftMouseArea
anchors.fill: parent
onClicked: leftClickedAnimation.start();
}
Text {
anchors.centerIn: parent
font.pixelSize: 30
color: "white"
text: "Click me!"
}
}
}
Column {
anchors.top: parent.top
anchors.right: parent.right
spacing: 20
Rectangle {
width: 290
height: 50
color: "lightGray"
MouseArea {
anchors.fill: parent
onClicked: container.state = "right"
}
Text {
anchors.centerIn: parent
font.pixelSize: 30
text: container.state==="right"?"Active":"inactive";
}
}
Rectangle {
id: rightRectangle
width: 290
height: 200
color: "blue"
MouseArea {
id: rightMouseArea
anchors.fill: parent
onClicked: rightClickedAnimation.start();
}
Text {
anchors.centerIn: parent
font.pixelSize: 30
color: "white"
text: "Click me!"
}
}
}
// 中央的提示文字
Text {
id: activeText
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
anchors.bottomMargin: 50
font.pixelSize: 30
color: "red"
text: "Active area clicked!"
// 透明
opacity: 0
}
SequentialAnimation {
id: leftClickedAnimation
// 将颜色变为白色(马上)
PropertyAction {
target: leftRectangle
property: "color"
value: "white"
}
// 将白色变为绿色
ColorAnimation {
target: leftRectangle
property: "color"
to: "green"
duration: 3000
}
}
SequentialAnimation {
id: rightClickedAnimation
PropertyAction {
target: rightRectangle
property: "color"
value: "white"
}
ColorAnimation {
target: rightRectangle
property: "color"
to: "blue"
duration: 3000
}
}
SequentialAnimation {
id: activeClickedAnimation
// 中间文件显现(立马)
PropertyAction {
target: activeText
property: "opacity"
value: 1
}
// 中间文字隐藏
PropertyAnimation {
target: activeText
property: "opacity"
to: 0
duration: 3000
}
}
Connections {
id: connections
onClicked: activeClickedAnimation.start()
}
states: [
State {
name: "left"
StateChangeScript {
script: connections.target = leftMouseArea
}
},
State {
name: "right"
StateChangeScript {
script: connections.target = rightMouseArea
}
}
]
Component.onCompleted: {
state = "left"
}
}
}
}
代码的思路:当我们设置 Connection 的 target 为一个元素(比如 MouseArea)的时候,那个元素的信号就会被 Conenction 接受并在其内部处理,这就导致MouseArea元素本身处理了一遍此信号,然后又由 Connection 处理了一遍此信号!所以你可以看到效果中不只按钮动画触发了,背景动画也触发了,前者是由MouseArea处理了鼠标按下消息,后者是Connection处理了鼠标按下消息!