处理来自Component.onCompleted的信号

时间:2014-06-18 16:55:01

标签: qt signals qml

我在同一目录中有两个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!")
 }
}

1 个答案:

答案 0 :(得分:4)

由于MyItem是在myLoader之前构建的,因此Connections对象尚未连接。您可以通过向每个对象的Component.onCompleted处理程序添加一些打印语句来看到这一点:

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)

            Component.onCompleted: print("Connections Component.onCompleted")
        }
    }
}

MyItem.qml

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