Search code examples
c++qtqwidgetremovechildqobject

Qt: RemoveWidget and object deletion


I have been reading Qt documentation and playing around with the qobject tree. I was wondering if there is a way to remove widgets from inside the tree that would delete them from memory.

When embedding qwidgets/qobjects in each other and creating the tree, removing a widget with removeWidget from the qlayouts would remove them visually in the gui however the object still remains attached to the parent qobject (object->parent() is not 0), it will only be deleted once its parent is deleted (such as going out of scope). I can only see that an qwidget can be destroyed only once the application terminates where the top widget wills everything underneath it (or if the object goes out of scope).

For example, say have a main window that has 2 stages: the first one has about 100 objects embedded from one parent and the other has 200. The application starts at stage 1 and moves to stage 2 where it will never go back to stage 1. If I wanted this to be somewhat efficient, I would try to kill all the objects in stage 1 (100 objects) but because they are attached to the root node of the main window, it cannot be destroyed even using "removeWidget".

I also tried to receive the pointer of a widget that was created without "new" operator and if I delete that object, the application would crash because it would call the destructor twice.

My question is, is there a way to remove a node in the qobject tree (where that node is not deleted because it is out of scope or when the application terminates)?

Sorry if this does not make that much sense. Thanks in advance.

Edit:

Sorry if I have given the wrong idea. My question is to remove a node from memory before the application terminates or before the object goes out of scope. This is an example (probably not that good).

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Test w;
    w.show();

    QHBoxLayout *layout = new QHBoxLayout();
    w.setLayout(layout);

    Test heavyObj;             //I know you can use pointers instead and that 
                               //would allow you to easy delete the object
                               //but say if I did this instead.
    w->addWidget(&heavyObj);

    for(int i=0; i < 200; i++) {
        Test obj(heavyObj);
    }

    w->removeWidget(&heavyObj); //At this point we don't want "heavyObj", I want
                                //to delete this object from memory
                                // is it possible to remove p1 from memory?

    return a.exec();

    //As stated, once the program terminates everything is destroyed
}

Solution

  • After calling removeWidget(), delete the object with delete yourWidgetPointer;. The destructor of the QObject will take care of unregistering the child with the parent.