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.
source share