Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to delete it? [Qt]

Tags:

qt

Do I have to delete objects from the heap in the example below? And if yes, how?

#include <QApplication>
#include <QTreeView>
#include <QListView>
#include <QTableView>
#include <QSplitter>

int main(int argc, char* argv[])
{
    QApplication app(argc,argv);
    QTreeView* tree = new QTreeView;
    QListView* list = new QListView;
    QTableView* table = new QTableView;
    QSplitter* splitter = new QSplitter;
    splitter->addWidget(tree);
    splitter->addWidget(list);
    splitter->addWidget(table);
    splitter->show();
//    delete splitter; WHEN TRYING TO DELETE I'M GETTING INFO THAT app  EXITED
//    delete table;    WITH CODE -1073741819
//    delete list;
//    delete tree;
    return app.exec();
}

Thank you for any help.

like image 303
There is nothing we can do Avatar asked Jan 19 '10 09:01

There is nothing we can do


2 Answers

Just allocate splitter on the stack. Then tree, list and table become children of splitter which takes ownership. When splitter gets deleted, all the children are deleted.

From Widgets Tutorial - Child Widgets:

The button is now a child of the window and will be deleted when the window is destroyed. Note that hiding or closing the window does not automatically destroy it. It will be destroyed when the example exits.

See also Object Trees and Object Ownership.

like image 103
Gregory Pakosz Avatar answered Oct 17 '22 15:10

Gregory Pakosz


Gregory Pakosz pointed out the proper solution, but I wanted to reiterate with a code example and to suggest you look into C++ object scope. Greg is accurate but did not clarify that putting splitter on the stack means that once it goes out of scope (the application exits) it will be deleted.

More accurately you should set a QObject's parent. When a parent object takes ownership of an another object it deletes it's children upon calling delete on the parent object. In QSplitters case, addWidget adds to QWidget's layout and the layout takes ownership of those objects.

#include <QApplication>
#include <QTreeView>
#include <QListView>
#include <QTableView>
#include <QSplitter>

int main(int argc, char* argv[])
{
    QApplication app(argc,argv);

    QTreeView* tree = new QTreeView;
    QListView* list = new QListView;
    QTableView* table = new QTableView;

    QSplitter splitter;

    splitter.addWidget(tree);
    splitter.addWidget(list);
    splitter.addWidget(table);
    splitter.show();

    return app.exec();
}

So simply making 'splitter' a local variable will cause it to be deleted when it goes out of scope. In turn, it's children will also be deleted.

  • http://doc.qt.io/qt-5/qtwidgets-tutorials-widgets-windowlayout-example.html
  • http://doc.qt.io/qt-5/qsplitter.html#addWidget
like image 27
Chris Avatar answered Oct 17 '22 15:10

Chris