我在同一目录中有两个qml文件,main.qml和MyItem.qml。单击鼠标区域时,单击消息"单击!"由onMessage main.qml成功处理。然而,消息"信号发送"绝不会被main.qml检索/处理。为什么呢?
main.qml:
import QtQuick 2.0
Item {
width: 100; height: 100
Loader {
id: myLoader
source: "MyItem.qml"
Connections {
target: myLoader.item
onMessage: console.log(msg)
}
}
}
MyItem.qml:
import QtQuick 2.0
Rectangle {
id: myItem
signal message(string msg)
width: 100; height: 100
Component.onCompleted: {
myItem.message("signal sent");
}
MouseArea {
anchors.fill: parent
onClicked: myItem.message("clicked!")
}
}
答案 0 :(得分:4)
由于MyItem
是在myLoader
之前构建的,因此Connections
对象尚未连接。您可以通过向每个对象的Component.onCompleted
处理程序添加一些打印语句来看到这一点:
import QtQuick 2.0
Item {
width: 100; height: 100
Loader {
id: myLoader
source: "MyItem.qml"
Connections {
target: myLoader.item
onMessage: console.log(msg)
Component.onCompleted: print("Connections Component.onCompleted")
}
}
}
import QtQuick 2.0
Rectangle {
id: myItem
signal message(string msg)
width: 100; height: 100
Component.onCompleted: {
print("MyItem Component.onCompleted")
myItem.message("signal sent");
}
MouseArea {
anchors.fill: parent
onClicked: myItem.message("clicked!")
}
}
qml: MyItem Component.onCompleted
qml: Connections Component.onCompleted