2

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.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
ProdoElmit
  • 1,067
  • 9
  • 22

1 Answers1

3

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?

Community
  • 1
  • 1
ProdoElmit
  • 1,067
  • 9
  • 22
  • You are right, check here : http://doc.qt.io/qt-5/qtqml-cppintegration-data.html#data-ownership . "Additionally, the QML engine respects the normal QObject parent ownership semantics of Qt C++ objects, and will never delete a QObject instance which has a parent." And also if you don't set cpp ownership explicitly on a QObject, QML will claim ownership by default. – Blabdouze Feb 16 '17 at 08:45
  • 2
    You can either pass a parent to keep C++ ownership (actually the parent is the owner then), or tell the QML engine that you expect the object to be owned by C++, using `QQmlEngine::setObjectOwnersship(object, QQmlEngine::CppOwnership)` – Kevin Krammer Feb 16 '17 at 09:09