When QStandardItemModel
, which is allocated on the stack, gets destroyed, what happens with objects to which pointers in the model are pointing at (e.g. item
/item2
pointer as in the following example):
QStandardItem* item = new QStandardItem("test");
QStandardItem* item2 = new QStandardItem("test2");
QList<QStandardItem*> list;
list.append(item);
list.append(item2);
QStandardItemModel model;
model.addRow(list);
In this context, if i understood correctly, row in a model is consisted of N values, each value in that row represented as QStandardItem
. This means that "list" object above is one row with two values (columns).
Is this better or worse than using model.setData()
, model.setRowCount()
and manually tracking coordinates?
If full context is needed, it's here. Idea is to manually loop over QSqlQuery
results and fetch rows in chunks. Relevant method is called loadChunk
.
If the model is stack allocated, do i need to somehow manage deallocation of items loaded to model via addRow()
TLDR; how to make sure that model doesn't leak memory when model is stack allocated, but contains a lot of pointers to objects on heap?
Note: It is QStandardItemModel::appendRow
, not QStandardItemModel::addRow
.
Now to the topic:
You do not need to worry about manually destroying QStandardItem objects. When the model they belong to is destroyed, so are they.
To demonstrate that inherit from QStandardItem and put a debug message in the destructor like this:
MyItem.h
#ifndef MYITEM_H
#define MYITEM_H
#include <QStandardItem>
class MyItem : public QStandardItem
{
public:
explicit MyItem(const QString &text);
~MyItem();
};
#endif // MYITEM_H
MyItem.cpp
#include "MyItem.h"
MyItem::MyItem(const QString &text) :
QStandardItem(text)
{
}
MyItem::~MyItem()
{
qDebug("Gone");
}
MainWindow.cpp
#include "MainWindow.h"
#include "MyItem.h"
#include <QStandardItemModel>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QStandardItemModel model;
auto *item = new MyItem("test");
model.appendRow(item);
}
You could also experiment with:
auto *model = new QStandardItemModel(this);
model->appendRow(item);
model->deleteLater();
In either cases the application should output "Gone" immediately after it is run.
By the way, the result will be the same when using model->removeRow(model->rowCount() - 1);
instead of model->deleteLater();
.
As for the QList<QStandardItem*> list;
in your code, list
is a local variable. It is used as a container to pass the items to the model. After that it is not necessary and is destroyed when it goes out of scope. The items however will continue to exist either until removed from the model or the model gets destroyed.