[Solved] Remove items from Layout



  • I wrote a program which receive the some test result from internet. The test result I received have to be displayed on the QWidget.

    Here is the design I have imagined: I can clear all items in the QVBoxLayout, and then fill the new content what I have received.

    I wrote some code according the logic above, and it does not work as what I thought. The executing screen shot:
    !http://img829.imageshack.us/img829/2040/removeitemfromlayout.png(::executing screen shot::)!

    It leaves some.... shadow or the items should be already remove all sqeezed in the first row.

    Is there any problem with my code?

    @

    int totalCount = ui->resultTextContainerLayout->count();
    for (int i = 0; i < totalCount; i++) {
        ui->resultTextContainerLayout->removeItem(ui->resultTextContainerLayout->itemAt(0));
    }
    //ui->resultTextContainerLayout->invalidate();
    
    for (int i = 0 ; i < eBoxDiskNum ; i++) {
        QLabel* tempLabel = new QLabel(ui->resultTextContainer);
        tempLabel->setFont(QFont("Calibri", 12));
        if (iErrCode & (1 << i)) {
            tempLabel->setStyleSheet("QLabel {color:red;}");
            tempLabel->setText(QString("Client%1 -> not ready").arg(i+1));
        } else {
            tempLabel->setStyleSheet("QLabel {color:black;}");
            tempLabel->setText(QString("Client%1 -> ready").arg(i+1));
        }
        ui->resultTextContainerLayout->addWidget(tempLabel);
    }
    ui->resultTextContainerLayout->addStretch();
    

    @



  • QLayout::removeItem() just removes the item from layout, but does not hide or delete it.
    @
    QLayoutItem *item;
    while ((item = ui->resultTextContainerLayout->takeAt(0)) != 0) {
    delete item;
    }

    for (int i = 0 ; i < eBoxDiskNum ; i++) {
    ...
    @

    Be aware that the above code only works for non-nested layouts (layouts only containing widgets). If you add nested layouts to your layout you will need a recursive removal. See "this":http://qt-project.org/forums/viewthread/13583/#71685 thread for further information.



  • Yes, it works.

    There are some difference between the code I tested which is I delete it using widget()

    @
    QLayoutItem *item = NULL;
    while ((item = ui->resultTextContainerLayout->takeAt(0)) != 0) {
    delete item->widget();
    }
    @

    Thank you very much



  • Be aware that not every item must be a widget! Your code actually works because <code>delete 0</code> is allowed in C++.



  • use this to clear all items inside a layout...

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

        delete child;
    }
    

    }@


Log in to reply
 

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