一、效果图
二、代码
#include "verticallayoutwidget.h"
#include "ui_verticallayoutwidget.h"
VerticalLayoutWidget::VerticalLayoutWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::VerticalLayoutWidget)
{
ui->setupUi(this);
for(int i=0;i<3;i++){
QLabel *label = new QLabel;
label->setStyleSheet("background:white");
label->setText("label"+QString::number(i));
ui->verticalLayout->addWidget(label);
}
}
VerticalLayoutWidget::~VerticalLayoutWidget()
{
delete ui;
}
void VerticalLayoutWidget::on_pushButton_clicked()
{
QLayoutItem *child;
while ((child = ui->verticalLayout->itemAt(0)) != nullptr) {
ui->verticalLayout->removeItem(child);
delete child->widget();
delete child;
child = nullptr;
}
}
三、总结
1.ui->verticalLayout->removeItem(child);只是将控件从布局管理器里移除,此时控件依然会在界面显示
2.delete child->widget();将对象销毁才可以使得控件不在界面展示