PDA

View Full Version : "new" + "delete" a QWidget and its children



vkincaid
18th January 2010, 21:27
If I understand the QWidget documentation correctly, there is no need to delete children widgets when deleting the parent widget.


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.


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!



#include <QApplication>
#include <QtAlgorithms>
#include <QMainWindow>
#include <QtGui/QLabel>
#include <QtGui/QTabWidget>

class B : public QWidget
{
public:
B() : mLabel(new QLabel(this))
{
printf("B constructor\n");
}

~B()
{
printf("B destructor delete label\n");
delete mLabel;
}

private:
QLabel* mLabel;
};


class A : public QMainWindow
{
public:
A() :
mLabel(new QLabel(this)),
mTab(new QTabWidget(this)),
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:
QLabel* mLabel;
QTabWidget* mTab;
B* mB;

};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

A* a = new A();
delete a;

return app.exec();
}

squidge
18th January 2010, 23:01
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.

axeljaeger
19th January 2010, 21:51
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.