How to connect a destroyed signal of C++ object from QML?

2.9k views Asked by At

I want to connect a destroyed signal of C++ QObject from QML so I did this:

Rectangle
{
    id: root
    width: 128
    height: 128

Button
{
    anchors.centerIn: parent
    text: "Click me"
    onClicked:
    {
        qobj.Component.onDestruction.connect(function(){console.log("It destroy")}) // qobj is set from c++
        qobj.destroy() // should output "It destroy"
    }
}

But nothing is printed when I destroy qobj.

1

There are 1 answers

5
peppe On BEST ANSWER

In the general case, you can connect to signals emitted from a C++ object using a Connections element:

Connections {
    target: yourObjectComingFromCpp
    onSomeSignal: console.log("Something")
}

or in Javascript by calling the connect function on the corresponding property of the JS-mapped object:

// without the *on*!
yourObjectComingFromCpp.someSignal.connect( /* JS function here */ );

However: this doesn't work for the specific QObject::destroyed signals, which are forcibly blacklisted and never available in QML (source).

I guess the reason is that the object is gone from the QML context anyhow at that point, plus when that signal is emitted you're deep into QObject's own destructor, which means any property or method access on your subclass is invalid at that point.