In many Qt tutorials, I see people doing this to add in a spacer in toolbar or status bar:
tb = my_toolbar;
QWidget* empty = new QWidget();
empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
tb->addWidget(empty);
tb->addWidget(otherWidget);
And they never do:
delete empty
at anywhere. Isn't this a memory leak? Why many people is still doing this way?
Right from the documentation:
QAction * QToolBar::addWidget(QWidget * widget)
Adds the given widget to the toolbar as the toolbar's last item.
The toolbar takes ownership of widget.
Therefore, the And they never do:
assumption is incorrect. The widget will be automatically destructed by the parent/child hierarchy mechanism supported in Qt. Here you can find the gist:
When QObjects are created on the heap (i.e., created with new), a tree can be constructed from them in any order, and later, the objects in the tree can be destroyed in any order. When any QObject in the tree is deleted, if the object has a parent, the destructor automatically removes the object from its parent. If the object has children, the destructor automatically deletes each child. No QObject is deleted twice, regardless of the order of destruction.