接收信号
要接收一个对象的信号, 需要定义一个进行处理方法,改方法由on+信号名构成.如下,声明了一个可以接收Button对象clicked信号的方法
Button {
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
text: "Change color!"
onClicked: {
rect.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
}
}
属性信号
QML属性的值更改时,会自动发出信号。这种类型的信号是属性更改信号,这些信号的信号处理程序以on+属性名+Changed的形式编写,其中,属性名称是首字母大写。
Button {
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
text: "Change color!"
onTextClicked: {
console.log("onTextClicked", text)
}
}
链接到一个信号
如下情况下可以使用Connections
对象来链接到一个信号
- 需要多个方法连接到同一信号
- 在信号发送器范围之外
- 连接到QML中未定义的目标
Rectangle {
id: rect
width: 250; height: 250
Button {
id: button
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
text: "Change color!"
}
Connections {
target: button
onClicked: {
rect.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
}
}
}
附加信号(Attached signal handlers)
import QtQuick 2.15
Rectangle {
width: 200; height: 200
color: Qt.rgba(Qt.random(), Qt.random(), Qt.random(), 1)
Component.onCompleted: {
console.log("The rectangle's color is", color)
}
}
向QML添加自己定义信号??
//语法
signal <name>[([<type> <parameter name>[, ...]])]
// SquareButton.qml
import QtQuick 2.15
Rectangle {
id: root
signal activated(real xPosition, real yPosition)
property point mouseXY
property int side: 100
width: side; height: side
TapHandler {
id: handler
onTapped: root.activated(mouseXY.x, mouseXY.y)
onPressedChanged: mouseXY = handler.point.position
}
}
// myapplication.qml
SquareButton {
onActivated: console.log("Activated at " + xPosition + "," + yPosition)
}
信号链接方法
import QtQuick 2.15
Rectangle {
id: relay
signal messageReceived(string person, string notice)
//建立链接
Component.onCompleted: {
relay.messageReceived.connect(sendToPost)
relay.messageReceived.connect(sendToTelegraph)
relay.messageReceived.connect(sendToEmail)
relay.messageReceived("Tom", "Happy Birthday")
}
//删除链接
function removeTelegraphSignal() {
relay.messageReceived.disconnect(sendToTelegraph)
}
function sendToPost(person, notice) {
console.log("Sending to post: " + person + ", " + notice)
}
function sendToTelegraph(person, notice) {
console.log("Sending to telegraph: " + person + ", " + notice)
}
function sendToEmail(person, notice) {
console.log("Sending to email: " + person + ", " + notice)
}
}
信号链接信号
Rectangle {
id: forwarder
width: 100; height: 100
signal send()
onSend: console.log("Send clicked")
TapHandler {
id: mousearea
anchors.fill: parent
onTapped: console.log("Mouse clicked")
}
Component.onCompleted: {
mousearea.tapped.connect(send)
}
}