3

I know that, when a QObject is destroyed, it also destroys all of its children. But, in all my recent Qt code, I've always been declaring the members of any class (say, a QMainWindow) as direct members, not pointer members, which makes Qt's memory management rarely (if at all) useful.

So, is this parenting property of QObjects used for something else? From the documentation, it isn't clear if QBoxLayout::addWidget() takes ownership of the widget (I think it doesn't). (When you add widgets to a layout, their parent will be set to the parent of the layout, as thuga, pointed out).

Romário
  • 1,234
  • 1
  • 16
  • 27
  • 3
    When you add widgets to a layout, [their parent will be set to the parent of the layout](http://doc.qt.io/qt-5/layout.html#tips-for-using-layouts) (the widget that contains the layout). – thuga May 27 '16 at 13:41
  • 3
    Besides destruction reasons, one good reason to set a parent is when you move objects to a new thread. When you move an object to a new thread, it moves all of its children to the new thread as well. – thuga May 27 '16 at 13:45
  • Your usage of Qt classes in no idiomatic. I suggest to use Qt classes as documentation proposes. – gomons May 27 '16 at 13:57

1 Answers1

3

There are other uses that come to mind:

  • when using moveToThread(), an entire object tree gets moved, not just the pushed object (otherwise, memory management becomes impossible);
  • QWidget extends the parent/child relation with new semantics, for instance:
    • children's coordinates are relative to the parent widget;
    • a parent widget will clip its children to its own geometry;
    • the order of the sibling widgets determines their z-ordering (stacking);
    • unhandled mouse/keyboard events propagate up in the hierarchy;
    • the parent of a top-level widget will make that top-level share the same taskbar entry and appear centered on top of the parent (typical case: dialogs).
peppe
  • 19,728
  • 3
  • 47
  • 65
  • In other words, it is really helpful to read the class description in the documentation :) RTFMB – dtech May 27 '16 at 20:22