I am writing an image viewer with Qt based on the QGraphicsScene feature of Qt. I am creating model of each image in a class called ImageModel and manage the display of the image in a class called ImageView. The ImageView class is as follows (just the part that is interesting):
class ImageView
{
public:
ImageView(QWidget *parent);
QGraphicsView * getView() {return view; }
private:
//qgraphics scene elements
QGraphicsScene *scene;
QGraphicsView *view;
QGraphicsPixmapItem *curItem;
};
The constructor for the class is as follows:
ImageView::ImageView(QWidget *parent)
{
//create scene and view with parent the main window
//such that the memory management is done by qt
scene = new QGraphicsScene(parent);
view = new QGraphicsView(parent);
view->setScene(scene);
}
Also I have pointer to an ImageView in my derivation of the QMainWindow.
My question is: should I let Qt do the memory management by seting my main window as parent of the view and the scene or should I take care of the memory management myself (leave the view and the scene without parents and delete them in the class destructors)? What is a good strategy in this case?
If you want the view to be nested inside the main window, then you will have to make it a child.
For your general question, this really comes down to your desired object lifetimes and ownership semantics. If you don’t want to the view/scene to outlive the main window then yes they should be children. You still have the option to delete them through other means at an earlier time.