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:

  1. QList<QStandardItem *> items;
  2. items.append(new QStandardItem("Item 1"));
  3. items.append(new QStandardItem("Item 2"));
  4. items.append(new QStandardItem("Item 3"));
  5. 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

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QStandardItemModel>
  6. #include <QStandardItem>
  7. #include <QDebug>
  8.  
  9. class DestroyedItem: public QStandardItem
  10. {
  11. public:
  12. DestroyedItem(const QString & text): QStandardItem(text)
  13. {
  14. qDebug() << "Item created" << this;
  15. }
  16.  
  17. ~DestroyedItem()
  18. {
  19. qDebug() << "Item destroyed" << this;
  20. }
  21. };
  22.  
  23. namespace Ui {
  24. class MainWindow;
  25. }
  26.  
  27. class MainWindow : public QMainWindow
  28. {
  29. Q_OBJECT
  30.  
  31. public:
  32. explicit MainWindow(QWidget *parent = 0);
  33. ~MainWindow();
  34.  
  35. private slots:
  36. void on_pushButton_clicked();
  37.  
  38. private:
  39. Ui::MainWindow *ui;
  40. QStandardItemModel *model;
  41. };
  42.  
  43. #endif // MAINWINDOW_H

mainwindow.cpp

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. #include <QSharedPointer>
  5.  
  6. MainWindow::MainWindow(QWidget *parent) :
  7. QMainWindow(parent),
  8. ui(new Ui::MainWindow)
  9. {
  10. ui->setupUi(this);
  11. model = new QStandardItemModel(ui->tableView);
  12. // Set the column headings of the table
  13. model->setHorizontalHeaderLabels(QStringList() << "Column 1" << "Column 2" << "Column 3");
  14.  
  15. QList<QStandardItem *> items;
  16. items.append(new DestroyedItem("Item 1"));
  17. items.append(new DestroyedItem("Item 2"));
  18. items.append(new DestroyedItem("Item 3"));
  19. model->appendRow(items);
  20.  
  21. // We set the model into the QTableView object
  22. ui->tableView->setModel(model);
  23. ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
  24. }
  25.  
  26. MainWindow::~MainWindow()
  27. {
  28. delete ui;
  29. }
  30.  
  31. void MainWindow::on_pushButton_clicked()
  32. {
  33. model->clear();
  34. }

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 .

  1. Item created 0x16e3540
  2. Item created 0x16ecdd0
  3. Item created 0x16e4e80
  4. Item destroyed 0x16e3540
  5. Item destroyed 0x16ecdd0
  6. 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
  • 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, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup