
Originally Posted by
jove04
My question is when are the hundreds of the QStandardItem *stdd I created in a loop are deleted from memory? Do I have to delete them manually by using delete stdd or they are deleted automatically when the model is deleted? What about the model itself? When is it removed from memory.
From the docs for QStandardItemModel::setItem()
The model takes ownership of the item.
The items will definitely be destroyed when the model itself is destroyed. They probably will be destroyed earlier if you use clear() on the model but I have not verified that.
The model itself, in this situation, will definitely be destroyed when the the object "this" is destroyed unless you choose to do it yourself earlier. When you create a QObject with a parent, or set the parent directly or indirectly after creation, then the parent will delete it as part of parent's destruction. See the the article "Object Trees and Object Ownership" in Assistant and the detailed description section of the QObject docs.
Edit: Just did the experiment, clear() does trigger item delete
#include <QtGui>
#include <QDebug>
{
public:
qDebug() << "Item created" << this;
}
~MyItem() {
qDebug() << "Item destroyed" << this;
}
};
int main(int argc, char *argv[])
{
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
new MyItem
(QString("row %0, column %1").
arg(row
).
arg(column
));
model.setItem(row, column, item);
}
}
qDebug() << "Finished making model";
model.clear();
qDebug() << "Model cleared";
}
#include <QtGui>
#include <QDebug>
class MyItem: public QStandardItem
{
public:
MyItem(const QString & text): QStandardItem(text) {
qDebug() << "Item created" << this;
}
~MyItem() {
qDebug() << "Item destroyed" << this;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStandardItemModel model(4, 4);
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
QStandardItem *item =
new MyItem(QString("row %0, column %1").arg(row).arg(column));
model.setItem(row, column, item);
}
}
qDebug() << "Finished making model";
model.clear();
qDebug() << "Model cleared";
}
To copy to clipboard, switch view to plain text mode
Added after 5 minutes:
mnh1959: If the "user defined data" is a value type then sure. If it is a pointer then the space for the pointer is freed but object pointed to is not. You have to manage the target of the pointer yourself (in the destructor of a QStandardItem derivative).
Bookmarks