Reputation: 14505
I am pretty confused about one thing in Qt:
You often add new actions to QMenu like this:
menu.addAction(new QAction("this is a menu"));
so you are creating a new object but who is deleting it? According to https://qt-project.org/forums/viewthread/25717 the parent object should take care of that but... does it always happen? What if I didn't put any parent object in constructor? What if I deleted the object myself, will parent object SEGFAULT as it deletes object that was already deleted?
Even default code that is created by qt creator is creating object called ui
in constructor and deletes it in destructor. That is what I was doing for my own objects that I created on the fly, but surprisingly, it never crashed. I just figured out that all the time I probably shouldn't have even delete them myself?
What is a proper way to deal with this? Does it apply for all QObjects that had a pointer to parent object in constructor?
Bonus question: if these objects are deleted by parent's destructor, does it mean that if parent is main window of application that is closed on exit only, that all new objects will just leak until the application is closed?
Upvotes: 1
Views: 1374
Reputation: 4360
If you want a QObject
to be automatically deleted, you must specify a parent. Most derived classes provide for this in one or more of their constructor parameters.
The QAction
you created above does not have a parent so it will not be deleted when the QMenu
is destroyed. To make it do so, change the line to be:
menu.addAction(new QAction("this is a menu", &menu));
This is not advisable though since QAction
is an implementation of the command pattern so it is intended to be used in more places than a QMenu
and thus its lifespan must not be tied to that of the QMenu
. A simple example would be as a button on a QToolBar
.
For this reason, the QMenu
does not make itself the parent of the QAction
when you add it.
Some other derived classes of QObject
do indeed do this so it is not always necessary to explicitly assign a parent yourself.
One common example is QMainWindow
. Whenever you assign a QWidget
using setCentralWidget()
, the main window will take ownership and force itself to be the parent of the new central widget, even if you made some other object that widget's parent.
Upvotes: 1