In Qt, can I embed child widgets in their parent via composition, or do I have to create them with new
?
class MyWindow : public QMainWindow
{
...
private:
QPushButton myButton;
}
MyWindow::MyWindow ()
: mybutton("Do Something", this)
{
...
}
The documentation says that any object derived from QObject
will automatically destroyed when its parent is destroyed; this implies a call to delete
, whcih in the above example would crash.
Do I have to use the following?
QPushButton* myButton;
myButton = new QPushButton("Do Something", this);
EDIT
The answers are quite diverse, and basically boil down to three possibilities:
- Yes, composition is ok. Qt can figure out how the object was allocated and only
delete
heap-allocated objects (How does this work?) - Yes, composition is ok, but don't specify a parent, since the parent would otherwise call
delete
on the object (But won't a parent-less widget turn into a top-level window?) - No, widgets always have to be heap-allocated.
Which one is correct?