Destroy objects QWidget of Qt

0

How should I destroy the Qt objects used to create the GUIs, for example the QPushButton , QLabel , etc., I should call delete manually or the framework manages the memory release.

QPushButton *btn = new QPushButton("Button");
QLabel *lbl = new QLabel("Label");

When finished you should do something like this, or not:

delete btn;
delete lbl;  
    
asked by nullptr 10.09.2017 в 22:53
source

1 answer

0

If the object does not have a parent you are in charge of creating it and destroying it:

QWidget* widget = new QWidget;
// ...
delete widget;

Now, at the moment in which that widget has a father, it is the father who is going to take charge of the life cycle of the widget ... When the father dies, the child will be automatically deleted:

QWidget* widget = new QWidget(parent);

// delete widget;

Of course you can always delete the widget manually, in this case the widget will be separated from the parent before erasing ... but beware, because if the parent has already deleted the child you can end up doing a double delete with dire consequences for your application:

QWidget* parent = new QWidget;
QWidget* child1 = new QWidget(parent);
QWidget* child2 = new QWidget(parent);

delete child1; // ok;
delete parent; // ok
delete child2; // double delete

So my advice is that whenever possible you let Qt manage the life of your objects.

    
answered by 13.09.2017 / 12:40
source