"new" + "delete" a QWidget and its children
If I understand the QWidget documentation correctly, there is no need to delete children widgets when deleting the parent widget.
Quote:
QWidget::QWidget ( QWidget * parent = 0, Qt::WindowFlags f = 0 )
Constructs a widget which is a child of parent, with widget flags set to f.
If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted.
Quote:
QWidget::~QWidget ()
Destroys the widget.
All this widget's children are deleted first. The application exits if this widget is the main widget.
However, I wrote the following test program, where I intentionally delete the children widgets in the parent's destructor and it deleted everything just fine. So it seems that I do need to explicitly delete the children widgets before deleting the parent widget, else it might lead to memory leak. But then I don't understand what the quoted QWidget documentation above. Can someone please explain to me what's the correct way? Thanks a bunch!
Code:
#include <QApplication>
#include <QtAlgorithms>
#include <QMainWindow>
#include <QtGui/QLabel>
#include <QtGui/QTabWidget>
{
public:
B
() : mLabel
(new QLabel(this)) {
printf("B constructor\n");
}
~B()
{
printf("B destructor delete label\n");
delete mLabel;
}
private:
};
{
public:
A() :
mB(new B())
{
printf("A constructor\n");
mTab->addTab(mB, "B");
}
~A()
{
printf("A destructor delete label\n");
delete mLabel;
printf("A destructor delete B\n");
delete mB;
printf("A destructor delete tab\n");
delete mTab;
}
private:
B* mB;
};
int main(int argc, char *argv[])
{
A* a = new A();
delete a;
return app.exec();
}
Re: "new" + "delete" a QWidget and its children
What is more likely happening is that when you delete the child, the child emits the destroyed() signal in its destructor and thus the parent removes that child from its list of children.
So you can free them, or you can let the parent objects free there childs. It's upto you. I know which I'd prefer however.
Re: "new" + "delete" a QWidget and its children
It is a feature of Qt that deleting QObjects is usually safe. If you connect two objects together using signals and slots and delete on of those, the connection is disconnected before so you have not dangling connections.