SOLVED: Remove widgets from Layout



  • Hello,
    How do I remove all widgets from a layout so as to leave it empty
    @
    QPushButton *button1 = new QPushButton("Button 1");
    QPushButton *button2 = new QPushButton("Button 2");
    ui->horizontalLayout->addWidget(button1);
    ui->horizontalLayout->addWidget(button2);
    @

    How do I empty ui->horizontalLayout?
    Thanks in Advance



  • I do not know of a method to remove all widgets at once, but if you have
    pointers to the widgets, you can remove them from the layout like this:
    @
    ui->horizontalLayout->removeWidget(button1);
    ui->horizontalLayout->removeWidget(button2);
    @



  • That would work, But I need to clear all the widgets in the first statement of the function. In otherwords, the widgets declared in the previous call are removed when the function is called. So at that point you can't use removeWidget()


  • Lifetime Qt Champion



  • As SGalst suggest, please read the documentation carefully.



  • I am doing it this way normally

    @
    QLayoutItem *wItem;
    if (!ui->widget->layout())
    ui->widget->setLayout(new QVBoxLayout());
    while ((wItem = ui->widget->layout()->takeAt(0)) != 0)
    {
    if (wItem->widget())
    wItem->widget()->setParent(NULL);
    delete wItem;
    }
    @

    Of course you can avoid the generation of the layout and the remove everything from the empty layout...



  • Supposing the contents of the Layout are widgets added with layout->addWidget(). How do I remove them? The methods above remove items of type QLayoutItem only



  • That's what the documentation for QLayoutItem says:

    bq.
    isEmpty() returns whether the layout item is empty. If the concrete item is a QWidget, it can be retrieved using widget(). Similarly for layout() and spacerItem().



  • Thanks butterface, But am just a Qt beginner. Could you please show me how to do it in case its a widget that I want to remove without using removeWidget().

    Code
    @QLayoutItem *child; //replace with widget
    while ((child = ui->HLayout->takeAt(0)) != 0) {
    delete child;
    }@



  • Without any testing and just the first guess this should look somehow like

    @
    QWidget *wItem;
    while ((wItem = ui->widget->widget()->takeAt(0)) != 0)
    {
    wItem->setParent(NULL);
    delete wItem;
    }
    @

    If this does not work please have a look at the documentation and come back here if that does not help.



  • Well, Thanks guys. I ended up using a widget container and did this:
    @QList<QWidget *> Widgets = ui->widget->findChildren<QWidget *>();
    foreach(QWidget * child, Widgets)
    {
    delete child;
    }@

    But now there is another problem: "Application crashes when removing tableWidget":http://qt-project.org/forums/viewthread/30727/


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.