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>
{
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();
}
#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();
}
To copy to clipboard, switch view to plain text mode
Bookmarks