Skogen
Skogen

Reputation: 721

handle signal from Component.onCompleted

I have two qml files in the same directory, main.qml and MyItem.qml. When the mousearea is clicked the message "clicked!" is successfully handled by onMessage main.qml. However the message "signal sent" is never retrieved/handled by main.qml. Why?

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!")
 }
}

Upvotes: 2

Views: 5505

Answers (1)

Mitch
Mitch

Reputation: 24416

Because MyItem is constructed before myLoader, so the Connections object hasn't even connected yet. You can see this by adding some print statements to the Component.onCompleted handler of each object:

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!")
    }
}

Output

qml: MyItem Component.onCompleted
qml: Connections Component.onCompleted

Upvotes: 5

Related Questions