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
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
  • ИМ
    Oct. 5, 2024, 4:51 p.m.
    Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
  • d
    July 5, 2024, 8:02 p.m.
    Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…