Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 665
Zz Tux Avatar asked Feb 10 '23 21:02

Zz Tux


1 Answers

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.

like image 147
peppe Avatar answered Feb 12 '23 13:02

peppe