PDA

View Full Version : Keeping QWidgets as private QWIdget subclass members



mtrpoland
31st December 2007, 17:31
Is it ok to declare for example QLabel as a private member of some CustomWidget class and "place" it in CustomWidget using setParent or Layouts...


class CustomWidget : public QWidget {
Q_OBJECT
public:
CustomWidget(QWidget *parent = 0);
private:
QLabel oneL;
};

What about Qt's "garbage collector" in this case?
Shall I rather keep pointers to QWidgets I want to use in my CustomWidget instance?
What differs these two methods?

marcel
31st December 2007, 18:02
Is it ok to declare for example QLabel as a private member of some CustomWidget class and "place" it in CustomWidget using setParent or Layouts...
It is ok for them to be private. No problem in that matter.



What about Qt's "garbage collector" in this case?
Shall I rather keep pointers to QWidgets I want to use in my CustomWidget instance?
Yes, you should rather use pointer members, in order to have the guarantee that the parent QObject will successfully delete its children. If you do this then you also have to make sure that all QObject(or subclasses) members will be created with a QObject parent such that at some point in your application the object will be deleted, either manually deleted, with deleteLater or by setting the delete on close flag.



What differs these two methods?
deleteLater doesn't work properly if you allocate on the stack.

jpn
1st January 2008, 14:31
Here's one thread (http://www.qtcentre.org/forum/f-qt-programming-2/t-qt-widget-setparent-10561.html) worth reading. It will explain why shouldn't you allocate widgets on the stack.