Reputation: 2934
So I'm a little confused about Qt's memory management. I was looking at the beginning samples and tutorials and saw this
QApplication app(argc, argv);
QWidget window;
QLabel *label = new QLabel(QApplication::translate("windowlayout", "Name:"));
QLineEdit *lineEdit = new QLineEdit();
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(label);
layout->addWidget(lineEdit);
window.setLayout(layout);
window.setWindowTitle(
QApplication::translate("windowlayout", "Window layout"));
window.show();
return app.exec();
Which is just fine except that I don't see any freeing of memory when they create the new widgets, now is this just for the tutorial so they don't confuse people or is the memory management handled automatically by Qt. Cause looking at this I would have to believe that there was a memory leak because nothing was getting freed.
Upvotes: 5
Views: 3756
Reputation: 129944
Widgets are destroyed by their parents (when you call layout->addWidget
, for example, layout takes ownership of the passed widget), when those are destroyed. In your case, window
will get destroyed at the end of the scope (when app.exec
returns), which in turn will destroy the layout, which in turn will destroy label and the edit box.
Object Trees & Ownership in Qt docs.
Upvotes: 11
Reputation: 6329
Qt builds an internal tree of things (layouts, widgets, dialogs, ...) that are freed, whenever Qt thinks this is ok. This hierarchy is built with the parent-parameter in the constructor of "things" or whenever the responsibility is transferred by some other function call (like addWidget). So you are not even allowed to delete "things", when Qt or some widget has taken over responsibility. See the docs in Qt on this.
Upvotes: 1
Reputation: 3701
In Qt objects are freed based on the hierarchy. i.e. When QObject is freed all it's children will be freed (based on the parents passed as arguments to object constructor).
Upvotes: 0