PDA

View Full Version : Memory management of QAction



nilot
4th August 2016, 16:15
Hello,

I have a question with the following piece of code that can be found here (http://doc.qt.io/qt-5/qtwidgets-graphicsview-diagramscene-example.html)


QMenu *MainWindow::createColorMenu(const char *slot, QColor defaultColor)
{
QList<QColor> colors;
colors << Qt::black << Qt::white << Qt::red << Qt::blue << Qt::yellow;
QStringList names;
names << tr("black") << tr("white") << tr("red") << tr("blue")
<< tr("yellow");

QMenu *colorMenu = new QMenu(this);
for (int i = 0; i < colors.count(); ++i) {
QAction *action = new QAction(names.at(i), this);
action->setData(colors.at(i));
action->setIcon(createColorIcon(colors.at(i)));
connect(action, SIGNAL(triggered()), this, slot);
colorMenu->addAction(action);
if (colors.at(i) == defaultColor)
colorMenu->setDefaultAction(action);
}
return colorMenu;
}

According to the doc of QWidget::addAction(QAction *action), the ownership of action is not transferred to the QWidget, so I wonder if the memory of each action created are correctly released.

Thank you

d_stranz
4th August 2016, 17:24
I wonder if the memory of each action created are correctly released.

You create your QAction instances using "this" as the parent object instance. So when your MainWindow goes out of scope (presumably when your program exits, if you create it in main() as is the usual case), these instances will be deleted since they are children of MainWindow.

If you create them without a parent (eg. "new QAction( "Some text" );") then they will not be deleted until the runtime cleans up dangling memory when your program exits.

The reason why QAction ownership is not transferred to the widget when setting them on it is because QActions are designed to be shared - the same QAction instance can be assigned to a menu, toolbar, or anything else that can accept actions. This wouldn't be possible if there was a strict ownership hierarchy based on the widget to which the action was assigned.