From 10:00 CET Friday 22nd November we will adjust how the server works to deal with some recently reported problems. Therefore there may be a load problem, if you experience more problems than usual trying to access the forum then please PM AndyS or any of the moderators so they can inform me.


Qt Quick Windows app crashes when C++ try to access element (in range) of a vector



  • Hi,

    My Qt Quick application on Windows is experiencing a very weird crash.

    I have a QObject derived c++ class called QObjectVector that contains a QVector<QObject*> m_data to store some objects created on the heap. I have a Q_INVOKABLE QObject* QObjectVector::at(index) function for QML side to access elements in that vector.
    On the QML side, I have a bunch of buttons, each with a property currentObject, and the button text is bound to currentObject.name. when I scroll the mouse wheel, I manually update the currentObject of each button using the at function (the text get updated too by the binding).

    Strangely, and only sometimes, after an unpredictable number of fast scrolling, the program crashes (stopped working). After debugging, I found that the crashing happens when the at function access m_data[i]. I have made sure that i is within the valid range [0, m_data.size()), so it is not an index-out-of-range error. My guess is that, somehow, the QML engine deletes my objects on the heap when trying to manage memory.

    This problem is very weird and unpredictable, and solving it is very crucial to the development of my app, so please please please, any help will be appreciated.

    Thank you!

    Tommy



  • @TommyX said:

    My guess is that, somehow, the QML engine deletes my objects on the heap when trying to manage memory.

    You're right. When you return a QObject* from C++ to QML, the default behaviour is that the QML engine takes ownership of the object. You can change this, see: http://doc.qt.io/qt-5/qtqml-cppintegration-data.html and http://doc.qt.io/qt-5/qqmlengine.html#setObjectOwnership.



  • @Wieland

    Thank you so much! I added QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); when the object was created, and this apparently solves the problem :)