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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With