Home > Software design >  destroy non-Qwidget member variable in custom QWidget
destroy non-Qwidget member variable in custom QWidget

Time:10-01

For a custom QWidget class that contains both QWidget member variable and non-widget member variable, what is the proper way to write the destructor of the class? For example, I have

class CustomWidget: public QWidget {
    Q_OBJECT
    public:
        QWidget* x_widget; 
        SomeOtherClass* x_non_widget;
}

and set the parent of x_widget to this when creating it, how should I write the destructor? Should I just put delete x_non_widget in the destructor?

CodePudding user response:

QWidget inherits from QObject, so if its parent is set, then the object gets deleted automatically when the parent is being destroyed. Since you set this as parent, then the child x_widget gets automatically deleted when the parent CustomWidget instance is deleted. So no destructor is needed in this case.

Note however that if you put a widget into a layout, then it is re-parented (if it already had a parent) to the widget which holds the layout. But I guess this is not your case.

If your non-widget object is derived from QObject then you can set its parent too. And then you do not need to delete it in destructor because it will be deleted automatically the same way as widgets.

If your non-widget is not derived from QObject or you do not want to set a parent for it (for any reason, e.g. you move it to a thread), then you can wrap it in some owning/strong smart pointer such as std::unique_ptr, std::shared_ptr or QScopedPointer. Then it will be deleted automatically via the smart pointer. You do not need to delete it in the destructor either.

And only if you do not want to wrap it in any such an owning/strong smartpointer, you need to delete it in the destructor manually.

PS: Aside from the question you have, for non-owned members kept by pointer inherited from QObject you can also benefit from using QPointer, which is an extremely handy class which ensures automatic nullification of the pointer when the object gets deleted anywhere in the code. So no more invalid pointers to deleted QObjects... But unlike owning/strong smart pointers, QPointer does not ensure automatic object deletion.

  •  Tags:  
  • qt
  • Related