HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Deleting pointers in Qt5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
qt5deletingpointers

Problem

I am relatively new to the Qt framework and I was wondering if I should delete pointers in my program. I know that, in C++, if memory is not return it could lead to memory leak, but I am not sure if the same applies to Qt.

#include "mainwindow.h"
#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget *w = new  QWidget();
    w->setWindowTitle("Music Player");
    QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
    w->setWindowIcon(*mainwind_icon);

    QPushButton * enter_button = new QPushButton();
    QTextEdit  * textbox = new QTextEdit();

    QHBoxLayout * vlayout = new QHBoxLayout;
    vlayout->addWidget(textbox);
    vlayout->addWidget(enter_button);

    w->setLayout(vlayout);

    w -> show();

    return a.exec();
}

Solution

In Qt, there is a concept of parents and a hierarchy.

In essence, it means that when a qobject owns another qobject (the other qobject's parent is the first) then the parent will take care of cleaning its children.

There are 2 ways an object becomes a child of another: when it is set in the constructor or when reparented. The qwidget family automatically reparents widgets which you add to it

Common use for the main function is to allocate the root statically and all the rest dynamically as child of the root:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w ();
    w.setWindowTitle("Music Player");
    QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
    w.setWindowIcon(*mainwind_icon);

    QPushButton * enter_button = new QPushButton();
    QTextEdit  * textbox = new QTextEdit();

    QHBoxLayout * vlayout = new QHBoxLayout;
    vlayout->addWidget(textbox);
    vlayout->addWidget(enter_button);

    w.setLayout(vlayout);

    w.show();
    return a.exec();
}


The setlayout takes ownership of the vlayout and its children so the destructor of w will delete those as well

When you are inside an event loop then you can delete a qobject by calling deleteLater on it which will schedule the object (and its children) for deletion. You can also connect a signal to it if needed.

Code Snippets

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w ();
    w.setWindowTitle("Music Player");
    QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
    w.setWindowIcon(*mainwind_icon);

    QPushButton * enter_button = new QPushButton();
    QTextEdit  * textbox = new QTextEdit();

    QHBoxLayout * vlayout = new QHBoxLayout;
    vlayout->addWidget(textbox);
    vlayout->addWidget(enter_button);

    w.setLayout(vlayout);

    w.show();
    return a.exec();
}

Context

StackExchange Code Review Q#43189, answer score: 12

Revisions (0)

No revisions yet.