Using Pointers for QObject Attributes

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

I know that QObjects remove their children, but should we not avoid using pointers, unless really necessary?

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

File Widget.h:

#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 the 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 the Widget.h file, will this be the reason for using pointers?

And I want to add that I saw the same question in StackOverflow, but the answer was that widgets should live between function calls, but this is achieved by using them as attributes.

+4
source share
2 answers

Here, apparently, a rather long discussion on the same issue:
Class member: pointer or variable

Some of the points in this link talk about:

  • Long-living and short-living objects
  • Pile with stack
  • Guaranteed order of destructors based on parents installed at facilities

It seems that there is no hard and fast rule to take away here, but rather in each case. Since I am also currently moving from PyQt -> Qt and choosing my C ++, my limited opinion so far is that I always use pointers for class members that are subclasses of QObject. I just feel that I know that they will only be destroyed using the parenting process - Qt →.

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

+5
source

Maybe just use a different constructor than the standard one?

0
source

All Articles