QObject gets destroyed after being put into QML va

2019-07-24 15:40发布

问题:

Today I've faced strange bug in our program. The object of a class inherited from QObject was being deleted by event with type QEvent::DefferedDelete, while nobody could possibly send it.

It was passed into QML as QVariant:

// cpp: 
        Q_INVOKABLE QVariant currentDevice_v() const {
            return QVariant::fromValue(_current);
        }
// qml: 
       Component.onCompleted: {
            curDevice = devicesModel.currentDevice_v()
            #...
       }

Without that qml line everything worked well - nothing produces delete event.

回答1:

What I've figured out that if I set the parent of that QObject before I pass it into QML, then it doesn't get deleted. So, I've concluded that passing unparented QObject into QML scope makes that scope become a parent of QObject and call its destructor after scope ends.

Sharing this out, as I haven't found an answer anywhere. But while writing this post I've found similar unanswered issue: Qt5.6 QML, why are dynamic models destroyed after garbage collection?



标签: qt qml qtquick2