Evgenii Legotckoi
Jan. 22, 2017, 9:33 p.m.

Qt/C++ - Lesson 059. Do I need to delete QStandardItem object from the memory after the call clear method in a data model?

When working with tables, and generally with different data in C ++ requires control over the removal to avoid memory leaks. But whether you want a total control of the removal of QStandardItem objects placed in QStandardItemModel , which has caused a clear method?

Such a question may arise on the basis of the manner in which QStandardItem objects are usually added in QStandardItemModel , namely:

QList<QStandardItem *> items;
items.append(new QStandardItem("Item 1"));
items.append(new QStandardItem("Item 2"));
items.append(new QStandardItem("Item 3"));
model->appendRow(items);

And so on in the cycle to fill the required number of rows. At the same pointers to data objects anywhere in the code will no longer appear and are not removed. Therefore, the question arises as to what happens if you call a clear method.

When an QStandardItem object is passed to QStandardItemModel , the ownership of these assets are transferred to the model. And when the method is clear model automatically removes the objects from memory.


Below, the following code demonstrates this.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QDebug>

class DestroyedItem: public QStandardItem
{
public:
    DestroyedItem(const QString & text): QStandardItem(text)
    {
        qDebug() << "Item created" << this;
    }

    ~DestroyedItem()
    {
        qDebug() << "Item destroyed" << this;
    }
};

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    QStandardItemModel *model;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSharedPointer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    model = new QStandardItemModel(ui->tableView);
    // Set the column headings of the table
    model->setHorizontalHeaderLabels(QStringList() << "Column 1" << "Column 2" << "Column 3");

    QList<QStandardItem *> items;
    items.append(new DestroyedItem("Item 1"));
    items.append(new DestroyedItem("Item 2"));
    items.append(new DestroyedItem("Item 3"));
    model->appendRow(items);

    // We set the model into the QTableView object
    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    model->clear();
}

The appearance of application

In this case, the window has QTableView that is QStandardItemModel , as well as present a QPushButton , by pressing on which the data model is cleared.

QDebug output

In the qDebug() output we will see how destructors of QStandardItem triggered by pressing on a QPushButton .

Item created 0x16e3540
Item created 0x16ecdd0
Item created 0x16e4e80
Item destroyed 0x16e3540
Item destroyed 0x16ecdd0
Item destroyed 0x16e4e80

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…