The QObject
implementation of the Composite Design Pattern has been tried and tested through the many versions of Qt.
The pattern requires that the composite object takes ownership of the children so, as long as the parenting has been done, you can be assured that the child QObjects
will be destroyed when the parent is destroyed.
Standard practice is to create child objects in heap memory and parent them immediately. If you don't parent immediately, you can explicitly parent using the setParent()
function, or else parenting will be done automatically when you add the widget to a parent widget, either using addWidget()
or addLayout()
.
QLayout
objects are size and layout managers of other QLayouts
and of QWidgets
. They don't own the objects they manage. The parent is actually the QWidget
that the QLayout
is the child of.
You have a choice to create the root parent in stack memory or in heap memory.
If you feel more comfortable with smart pointers, there are two classes that are specifically for QObjects
: QPointer and QSharedPointer. Each has their pros and cons.
#include
#include
#include
#include
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QWidget widget; // Root parent so can create as a auto-deleting object on the stack
QHBoxLayout *layout = new QHBoxLayout(&widget); // Create on the heap and parent immediately
QLabel *label = new QLabel("label", &widget); // Create on the heap and parent immediately
layout->addWidget(label); // widget remains label's parent
widget.setLayout(layout); // widget is changed to layout's parent if necessary, as well
// as any widgets that layout manages
widget.show();
return app.exec();
// layout and label are destroyed when widget is destroyed
}