Search code examples
c++qtqtwidgets

When I dynamically add widgets on windows should I specify parent?


Should I do:

auto btnDelete = new QPushButton(this);
btnDelete->setText("Delete");

or is it safe to do:

auto btnDelete = new QPushButton("Delete");

And why?

I add it with: this->ui->formLayout->addRow(btnDelete, editForm);


Solution

  • It is perfectly safe. The moment you add it to a layout, the layout will set the parent for you. To whatever widget is owner of layout. The moment the parent is deleted it will also call the deconstructer of your pushbutton