Oshada
Oshada

Reputation: 112

Does closing a QDialog window delete its dynamically added UI elements?

I have a QDialog window in my application and I am dynamically adding a QComboBox for its layout through this code

Orderdialog.cpp

void Orderdialog::addElements()
{
    ui->setupUi(this);
    msgComboBox = new QComboBox();
    lbl = new QLabel();
    lbl->setText("Message");
    ui->formLayout->addRow(lbl,msgComboBox);    
}

(msgComboBox & lbl is defined in the header file)

According to this question setting an attritubte will delete the dialog object when its close() event is executed.

What I want to know is whether it deletes these dynamically added msgComboBox & lbl or do I need to manually delete them in the destructor of Orderdialog class?

Upvotes: 2

Views: 2029

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

In Qt:

  • When the QObjects are destroyed they destroy their children.
  • When a QWidget is closed, it is not deleted, except when the Qt::WA_DeleteOnClose attribute is established.

A QWidget is a QObject so it also meets the first point, so that a QWidget is the children of another QWidget there are at least 3 possibilities:

  • You pass the parent QWidget in the constructor.
  • You use the setParent() method.
  • And when you establish it through a layout since your parent will be the widget to which the layout was established.

In the case of lbl and msgComboBox being passed to a layout this will be the childrens of the QWidget that was established, as I do not know the .ui could not say who is his parent but I can say that there is a relationship of kinship with the window.

So when the window is destroyed your children will also be destroyed, and these children will destroy their children, so lbl and msgComboBox will be destroyed, so you only have to setAttribute(Qt::WA_DeleteOnClose) so that lbl, msgComboBox and the same Orderdialog are deleted when the window is closed.

Upvotes: 4

Related Questions