[Solved] Remove items from Layout
-
wrote on 11 May 2012, 02:46 last edited by
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();
@
-
wrote on 11 May 2012, 06:30 last edited by
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.
-
wrote on 11 May 2012, 08:25 last edited by
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
-
wrote on 11 May 2012, 10:21 last edited by
Be aware that not every item must be a widget! Your code actually works because <code>delete 0</code> is allowed in C++.
-
wrote on 8 Jun 2014, 14:01 last edited by
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; }
}@