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.
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?
来源:https://stackoverflow.com/questions/42254141/qobject-gets-destroyed-after-being-put-into-qml-variable