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!

Qt Code:
  1. #include <QApplication>
  2. #include <QtAlgorithms>
  3. #include <QMainWindow>
  4. #include <QtGui/QLabel>
  5. #include <QtGui/QTabWidget>
  6.  
  7. class B : public QWidget
  8. {
  9. public:
  10. B() : mLabel(new QLabel(this))
  11. {
  12. printf("B constructor\n");
  13. }
  14.  
  15. ~B()
  16. {
  17. printf("B destructor delete label\n");
  18. delete mLabel;
  19. }
  20.  
  21. private:
  22. QLabel* mLabel;
  23. };
  24.  
  25.  
  26. class A : public QMainWindow
  27. {
  28. public:
  29. A() :
  30. mLabel(new QLabel(this)),
  31. mTab(new QTabWidget(this)),
  32. mB(new B())
  33. {
  34. printf("A constructor\n");
  35. mTab->addTab(mB, "B");
  36. }
  37.  
  38. ~A()
  39. {
  40. printf("A destructor delete label\n");
  41. delete mLabel;
  42. printf("A destructor delete B\n");
  43. delete mB;
  44. printf("A destructor delete tab\n");
  45. delete mTab;
  46. }
  47.  
  48. private:
  49. QLabel* mLabel;
  50. QTabWidget* mTab;
  51. B* mB;
  52.  
  53. };
  54.  
  55. int main(int argc, char *argv[])
  56. {
  57. QApplication app(argc, argv);
  58.  
  59. A* a = new A();
  60. delete a;
  61.  
  62. return app.exec();
  63. }
To copy to clipboard, switch view to plain text mode