Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Qt Quick Windows app crashes when C++ try to access element (in range) of a vector
TommyX last edited by TommyX
My Qt Quick application on Windows is experiencing a very weird crash.
I have a
QObjectderived c++ class called
QObjectVectorthat contains a
QVector<QObject*> m_datato 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
currentObjectof each button using the
atfunction (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
m_data[i]. I have made sure that
iis 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.
A Former User last edited by A Former User
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.
TommyX last edited by
Thank you so much! I added
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);when the object was created, and this apparently solves the problem :)