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