前言: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文章来源:https://www.toymoban.com/news/detail-640652.html
#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文章来源地址https://www.toymoban.com/news/detail-640652.html
#include "mypushbutton.h"
myPushButton::myPushButton(QWidget *parent) : QPushButton(parent)
{
}
myPushButton::~myPushButton()
{
qDebug() << QStringLiteral("按钮被析构");
}
到了这里,关于QT 正确删除Layout的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!