Important: Please read the Qt Code of Conduct -

[solved] Delete all Items from Layout

  • I need your help again.
    I have an Dialog with an QVBoxLayout. I'll add QHBoxLayouts with Labels and Spinbox to the QVboxLayout with an function. How can i delete all Items when the dialog is deleted??
    In my case the Dialog's destructor deletes the QVBoxLayout. But all other layouts with the objects i added in the function will not be deleted. How can i do that?? I looked for an property to make the layout delete all items in the destructor, but i haven't found such an property.

  • Lifetime Qt Champion


    Have you tried to set the parent of the inserted widgets to the dialog ?
    (not sure it works)

    Alternatively you could kill em all

    void remove ( QLayout* layout )
        QLayoutItem* child;
        while ( layout->count() != 0 ) {
            child = layout->takeAt ( 0 );
            if ( child->layout() != 0 ) {
                remove ( child->layout() );
            } else if ( child->widget() != 0 ) {
                delete child->widget();
            delete child;

    from dialog
    remove ( ui->gridLayout );

    Im not sure its the best way to do it but it does show how to delete them all :)

  • I tried to add the widget as parent, but i'm not sure if it'll delete everything. How can i check that??

  • Lifetime Qt Champion

    Well make a new widget that inherited a button and place it in your layout,
    and place a break point in its destructor.

    How did you know before it did not get deleted?

  • well i have this function:

    void SellHouseDialog::addStreet(QString name, int house)
    	QHBoxLayout* hLayout = new QHBoxLayout(this);
    	// set Streetname
    	hLayout->addWidget(new QLabel(name, this));
    	// setup the spinbox
    	QSpinBox* box = new QSpinBox(this);
    	box->setRange(0, house);

    and the documentation of the QVBoxLayout's destructor says
    "Destroys this box layout.

    The layout's widgets aren't destroyed."

    So i know that they were not deleted ;) I added the widget as parent, and run with the debugger through the whole destructor (much time later) the destructor from QLable and QSpinbox where called. So now i know that everything is cleaned up :D

    Thank you very much

  • Lifetime Qt Champion

    Ok super
    so parent(ing) did work.

    I was not sure so good you report back so I learn new stuff too.

    Heh yeah, debugging the whole shutdown is many steps :)

    Have a nice evening

  • @mrjj

    yes debugging the whole destructor are many steps. My F11 key is still blazing.

    ähm and it's afternoon for me :D but thanks