Do I need to delete it? [Qt]

Do I need to delete objects from the heap in the example below? And if so, 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();
}

Thanks for any help.

+5
source share
3 answers

Just select splitteron the stack. Then tree, listand tablebecome children splitter, which become property. When splitterremoved, all children are removed.

From Widget Tutorial - Kids Widgets :

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

. .

+11

, ++. , , , ( ) .

, QObject. , delete . QSplitters addWidget QWidget, .

#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();
}

, "" . , .

+1

Instead of manually managing memory, you can let the compiler do this for you. At this point, you may ask: why use a bunch at all? You should keep things as costly as possible and let the compiler do the hard work.

Objects will be destroyed in the reverse order of declaration. Thus, first - the implicit parent - must be declared first so that he does not try to incorrectly remove his children. In C ++, the order of declarations makes sense!

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();
}
0
source

All Articles