QML学习笔记(十八)QML的信号处理器的Connections写法
前言
在我们此前的学习中,我们实现信号处理器时都是在当前组件代码的内部进行实现的。实际上,我们可以通过Connections写法,将信号处理器的相关实现代码放在外面。
一、Connections
这是此前的写法:
Window {visible: truewidth: 640height: 480title: qsTr("QmlConnections")Rectangle{id: rectIdwidth: 200height: 200color: "dodgerblue"MouseArea{id: mouseAreaIdanchors.fill: parentonClicked:{console.log("Clicked on the mouse area")}onDoubleClicked: mouse =>{console.log("Double clicked at: " + mouse.x + " ," + mouse.y)}}}
}
这是使用了Connections的写法:
Window {visible: truewidth: 640height: 480title: qsTr("QmlConnections")Rectangle{id: rectIdwidth: 200height: 200color: "dodgerblue"MouseArea{id: mouseAreaIdanchors.fill: parent}}Connections{target: mouseAreaIdfunction onClicked(){console.log("Clicked on the mouse area")}function onDoubleClicked(mouse){console.log("Double clicked at: " + mouse.x + " ," + mouse.y)}}
}
可以看到,使用了Connections便能将处理器代码放在外部,当写法会有所不同。
首先,我们要设置一个target,虽然是目标的意思,但实际上是源、信号的来源的意思,切记不要混淆。
然后我们使用function来实现处理器代码,这里需要加(),注意里面的参数mouse,这个需要和该接口的定义保持一致,如果有不清楚的记得查找帮助文档。
二、总结
本节内容比较简单,后面可能也会有篇幅较短的文章。原本想要几个知识点合并起来,但感觉还是单独分开写比较好,零碎点总好过显得混乱不堪。
这个Connections实际上功能还不止如此。
在C++代码发送信号,需要在qml进行接收的情形时,我们也需要使用到这个东西,并且它非常重要。这个将在学习C++和qml进行交互的时候,再进行学习和介绍。
