Jacob Krieg
Jacob Krieg

Reputation: 3164

Qt Memory Management for Qt objects

I know there are a lot of questions regarding qt memory management but i couldn't find an answer on mine.

So for the qt widgets, if you pass this(which is the parent widget) as parameter at the object creation, the parent widget takes ownership of it and deletes it when the parent dies. The same thing happens when you add a widget to a layout and set that layout on the widget.

But what happens if i declare a pointer to a QColor object for example? QColor can't be added as child for another widget or can't be added to a layout. Will the memory be released when the widget dies or i need to delete it manually in the destructor?

Here an example...what happens with m_pColor when Widget will be destroyed? Will it be destroyed or there will be a memory leak? Sorry for any mistakes in the code, i didn't compile it, i just wrote it here as example.

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class QHBoxLayout;
class QPushButton;
class QColor;

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget( QWidget *parent = NULL );

public:
    QHBoxLayout *m_pLayout;
    QPushButton *m_pButton;
    QColor *m_pColor;
};

#endif // WIDGET_H

#include "widget.h"

#include <QHBoxLayout>
#include <QPushButton>
#include <QColor>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_pLayout = new QHBoxLayout;
    m_pButton = new QPushButton( tr( "Button" ) );
    m_pLayout->addWidget( m_pButton );

    m_pColor = new QColor(0, 0, 0, 255);

    setLayout( m_pLayout );
}

Upvotes: 5

Views: 1316

Answers (2)

user1069861
user1069861

Reputation: 49

There is no reference for parent widget to destroy the m_pColor. you can use Valgrind to check for memory leak on this executable.

Upvotes: 2

UmNyobe
UmNyobe

Reputation: 22890

What you suggested is valid only for classes inheriting QObject (ie having QObject as one of their superclass). These properties don't apply to other classes (even built-inQt ). As QColor not a subclass of QObject, the object referenced by m_pColor will not be destroyed when Widget is destroyed. You will have to do it manually.

Upvotes: 6

Related Questions