Reputation: 3259
I started using Qt but I'm facing a big problem: I implemented my custom model that inhrerits from the QAbstractListModel class. What I want to do is to display a list with icon. All works and the image is shown with my code but it creates a memory leak. If I don't return the icon no memory leak is detected.
class MyModel : public QAbstractListModel
{
public:
...
private:
QIcon myicon;
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
...
if (role == Qt::DecorationRole)
{
return this->myicon;
}
...
}
EDIT 1
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
MyModel::MyModel(...)
{
...
ui.listWidget->addItem(new QListWidgetItem(QIcon("myicon"), "my text"));
}
Upvotes: 0
Views: 948
Reputation: 12547
I don't think memory leak is in the code, you showed.
QIcon
has conversion to QVarint
(defined with operator QVariant
), it widely used by standard item model/item widgets.
You also do not manage any pointers and do not use some explicit conversions.
So, this code seems OK, but it can be a memory in code, that uses icon.
Upvotes: 0
Reputation: 22890
I don't see a constructor of QVariant
with QIcon
as parameter, and I am surprised it compiles. As you are returning a QIcon
when a QVariant
is expected, there must be some crazy implicit conversions going. You have to know that in some cases when you create a QVariant
there is a deep copy of the initial object. Keep track of the qvariants you create and use QVariant::clear()
when you don't need them anymore.
EDIT:
By the way you are implicitly using the operator
QIcon::operator QVariant () const
which returns a QVariant
. this variant doesn't contain the initial QIcon
, but a deep copy. So follow my earlier advice to get rid of the leak.
Upvotes: 1