前言:QT中以代码的方式设置布局的函数是 *void QWidget::setLayout(QLayout *layout)*但是没有提供直接删除布局的函数。在删除布局时应该注意内存泄漏的问题。下面的方法仅供参考。
QLayoutItem *item;
if(this->layout() != nullptr)
{
while((item = this->layout()->takeAt(0)) != nullptr)
{
delete item->widget();
delete item;
}
delete this->layout();
}
参考文档takeat函数
以下是主要工程代码
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "mypushbutton.h"
#include <QVBoxLayout>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
sonWidget = new QWidget;
QPushButton *sonButton = new QPushButton(sonWidget);
sonWidget->hide();
myPushButton *button1 = new myPushButton;
button1->setText(QStringLiteral("按钮1"));
connect(button1, &QPushButton::clicked, this, [=](){
qDebug() << QStringLiteral("按钮1被点击");
});
myPushButton *button2 = new myPushButton;
button2->setText(QStringLiteral("按钮2"));
QVBoxLayout *box = new QVBoxLayout;
box->addWidget(button1);
box->addWidget(button2);
this->setLayout(box);
connect(button2, &QPushButton::clicked, this, [=](){
sonWidget->show();
});
connect(sonButton, &QPushButton::clicked, this, &Widget::slot_sonButton);
}
Widget::~Widget()
{
delete ui;
}
void Widget::slot_sonButton()
{
QLayoutItem *item;
if(this->layout() != nullptr)
{
while((item = this->layout()->takeAt(0)) != nullptr)
{
delete item->widget();
delete item;
}
delete this->layout();
}
QHBoxLayout *box = new QHBoxLayout;
myPushButton *button = new myPushButton;
box->addWidget(button);
this->setLayout(box);
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void slot_sonButton();
private:
Ui::Widget *ui;
QWidget *sonWidget;
};
#endif // WIDGET_H
mypushbutton.cpp
#include "mypushbutton.h"
myPushButton::myPushButton(QWidget *parent) : QPushButton(parent)
{
}
myPushButton::~myPushButton()
{
qDebug() << QStringLiteral("按钮被析构");
}