c++qtqwidgetqobject

Qt: Can child objects be composed in their parent object?


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:

Which one is correct?


Solution

  • The non-static, non-heap member variables are deleted when that particular object's delete sequence starts. Only when all members are deleted, will it go to the destructor of the base class. Hence QPushButton myButton member will be deleted before ~QMainWindow() is called. And from QObject documentation: "If we delete a child object before its parent, Qt will automatically remove that object from the parent's list of children". Hence no crash will occur.