Search code examples
c++qtpointersqobject

Using pointers for QObject attributes


Since I learned Qt, I've been confused by the fact that in the documentations, and books I've read, they use pointers for attributes that are instances of QObject subclasses, such as widgets.

I know that QObjects delete their children, but shouldn't we avoid using pointers except when it's really necessary?

here is a working example in which I don't use pointers:

Widget.h file:

#include <QSlider>
#include <QLabel>
#include <QVBoxLayout>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);

public slots:
    void change(int);
private:
    QSlider m_slider;
    QLabel m_label;
    QVBoxLayout m_layout;
};

and Widget.cpp file:

#include "Widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , m_slider(Qt::Horizontal)
    , m_label("0")
    , m_layout(this)
{
    m_layout.addWidget(&m_slider);
    m_layout.addWidget(&m_label);

    connect(&m_slider, SIGNAL(valueChanged(int)), this, SLOT(change(int)));
}

void Widget::change(int n){
    m_label.setText(QString::number(n));
}

the only difference here is that I have to include the header in Widget.h file, would that be the reason for using pointers?

And I want to add that I've seen some similar question on StackOverflow but the answer was that widgets should live between function calls, but that's achieved here when using them as attributes.


Solution

  • There seems to be a pretty lengthy discussion on this same question here:
    Class member: pointer or variable?

    Some of the points from this link talk about:

    • Long lived vs Short lived objects
    • Heap vs Stack
    • Guaranteed order of destructors based on the parents set on the objects

    It seems that the take away here is there isn't a hard and fast rule, but rather a case-by-case basis. As I am currently also migrating from PyQt -> Qt and picking up my C++, my limited opinion so far is that I always use pointers for class members that are QObject subclasses. I just feel like I know they will be destroyed only by the Qt parent->child destruction process.

    Again, this is a limited perspective. I am sure someone with strong C++ experience can offer a better answer. But the link I referred to does include very experienced Qt programmers.