Do I have to delete it? [Qt]

后端 未结 3 1542
臣服心动
臣服心动 2021-01-12 16:57

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

#include 
#include 
#include 

        
3条回答
  •  孤独总比滥情好
    2021-01-12 17:35

    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 
    #include 
    #include 
    #include 
    #include 
    
    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

提交回复
热议问题