简体   繁体   中英

Qt Widget Memory Management

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.

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.

In Qt objects are freed based on the hierarchy. ie When QObject is freed all it's children will be freed (based on the parents passed as arguments to object constructor).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM