Joe Staines
Joe Staines

Reputation: 321

Memory leak when transferring custom data (Type*) with QStandardItem?

I have a QTreeView with associated QStandardItemModel and QStandardItem's that fill the model. Then i also have a slot function that connects to clicked(QModelIndex) on the model and does some stuff. While building the model i would like to pass in some custom data to the QStandardItem's so that the slot function can do something with it. I managed to get this working through the method described here.

However i'm concerned about there being a possible memory leak with this method and what to do about it. If it does leak, i cant delete it from the associated slot function since the view will still be there and the user may click the same item again (and then point to a NULL reference) and im not totally sure about possible ways to enclose the pointer with a smart pointer because of the relationship with the Q_DECLARE_METATYPE(Object*) macro and how data is set to QStandardItemto

So does this cause a memory leak without an associated delete here and if it does, what are the best ways to get around this?

Upvotes: 1

Views: 370

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

If you declare a pointer as metatype, Qt will internally manage the pointer alone, so it's your responsibility to ensure that the object is deleted in due time (by deleting it manually and clearing references to it or assiging a parent to it and ensuring the parent is deleted. You can avoid memory leaks by using value-based metatype, e.g. Q_DECLARE_METATYPE(MyClass). However MyClass should have copy constructors so QObject will not do. You can also use shared pointers: Q_DECLARE_METATYPE(QSharedPointer<QObject*>). Qt will internally keep shared pointers and delete them when appropriate view items are removed, so the underlying object will be deleted if your code doesn't contain another shared pointers to it. Refer to QSharedPointer documentation to learn how to use it correctly.

Upvotes: 2

Related Questions