How to connect a destroyed signal of C++ object fr

2019-02-24 04:24发布

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条回答
成全新的幸福
2楼-- · 2019-02-24 05:06

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.

查看更多
登录 后发表回答