Do I have to delete objects from the heap in the example below? And if yes, how?
#include
#include
#include
Instead of managing the memory manually, you can let the compiler do it for you. At that point you may ask: why use the heap at all? You should keep things by value as much as feasible, and let the compiler do the hard work.
The objects will be destroyed in the reverse order of declaration. Thus the splitter - the implicit parent - must be declared first, so that it doesn't attempt to incorrectly delete its children. In C++, the order of declarations has a meaning!
int main(int argc, char* argv[])
{
QApplication app(argc,argv);
QSplitter splitter;
QTreeView tree;
QListView list;
QTableView table;
splitter.addWidget(&tree);
splitter.addWidget(&list);
splitter.addWidget(&table);
splitter.show();
return app.exec();
}
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.
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.