Solved How to free the memory usage of a qwidget?
-
I have a simple example
#ifndef TXTEDITOR_H #define TXTEDITOR_H #include <QWidget> namespace Ui { class TxtEditor; } class TxtEditor : public QWidget { Q_OBJECT public: explicit TxtEditor(QWidget *parent = 0, QString file = ""); ~TxtEditor(); private: Ui::TxtEditor *ui; }; #endif // TXTEDITOR_H
#include "txteditor.h" #include "ui_txteditor.h" #include <QPlainTextEdit> #include <QTextStream> TxtEditor::TxtEditor(QWidget *parent, QString file) : QWidget(parent), ui(new Ui::TxtEditor) { ui->setupUi(this); QPlainTextEdit *editor = ui->plainTextEdit; QFile f(file); if(f.open(QIODevice::ReadOnly|QIODevice::Text)){ QTextStream in(&f); editor->setPlainText(in.readAll()); } } TxtEditor::~TxtEditor() { delete ui; }
I use it as
TxtEditor *editor = new TxtEditor(NULL,"/boot/System.map-4.3.3"); editor->show();
I want to free all the memory used by editor when I close the editor window.
How to do that? -
overload
void TxtEditor::closeEvent(QCloseEvent *) { deleteLater(); }
Is this OK?
-
@Mr-Pang
Where do you create your TxtEditor? Can't it have a parent widget?
If you can set your widget a parent, then let Qt mechanisms handle the proper deletion for you.
Maybe you can consider creating your TxtEditor on the stack, depending on your scope. -
overload closeEvent seems to work.
-
There's an attribute specifically for that purpose:
TxtEditor *editor = new TxtEditor(nullptr, "/boot/System.map-4.3.3"); //you should really put "parent" as last param editor->setAttribute(Qt::WA_DeleteOnClose);