Destruction of QObjects



  • Hello,
    I have a question about correctly destroying QT Objects in the Destructor.

    void ClassA::Method1()
    {
        QAction* context1;
        context1 = new QAction(("text"), this);
    }
    void ClassA::Method2()
    {
        QStandardItemModel *model = new QStandardItemModel(1, 1);
        model->setData(...)
        ...->setModel();
    }```
    

    When should the objects be destroyed? Is it correct, that the destruction of QAction in this case is
    handled by QT, because of the "this"?
    What do I do with the Standarditemodel to avoid memory leaks?

    Thanks for help.



  • @TauCeti said in Destruction of QT Objects:

    When should the objects be destroyed? Is it correct, that the destruction of QAction in this case is handled by QT, because of the "this"?

    Yes. When ClassA gets deleted, QAction will be deleted too

    What do I do with the Standarditemodel to avoid memory leaks?

    pass a parent to that one too, QStandardItemModel *model = new QStandardItemModel(1, 1,this);



  • QStandardItemModel accepts this as third Parameter. QStandardItemModel::QStandardItemModel(int rows, int columns, QObject * parent = 0)

    And yes, when you add "this" to a Constructor then this Object gets a Parent of "this". But it depends what "this" is. As Example, if "this" is the MainWindow Object then yes, because MainWindow gets destroyed after you close it.

    Update: Someone was faster then me :P


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.