5

When adding a QAction* to a QMenu who is responsible for deleting the QAction* object? I couldn't find it mentioned in the documentation for QMenu or QAction.

void MyClass::contextMenuEvent(QContextMenuEvent *evt)
{
    QMenu menu(this);
    QAction *a = new QAction(tr("Some action"), this);
    menu.addAction(a); // who owns a?
    menu.exec(evt->globalPos());
}

The Qt Menus example doesn't delete any of the actions it creates so I assume that QMenu takes ownership of the QAction. Is that correct?

glennr
  • 2,069
  • 2
  • 26
  • 37

1 Answers1

5

If you add a pre-existing action to a QWidget (which QMenu is) then:

The ownership of action is not transferred to this QWidget.

Note that in your example, deletion of a is handled by MyClass because you have used it as a parent QObject, so a is deleted in QObject's destructor.

cmannett85
  • 21,725
  • 8
  • 76
  • 119
  • Thanks. Your answer is ambiguous regarding the destruction of "a". Will QObject do it for me or must I do it explicitly somewhere in MyClass? – glennr Jan 06 '12 at 00:22
  • 1
    Each QObject maintains a list of QObjects that it is the 'parent' of, when the QObject is destroyed it's 'children' are deleted too. So no, you don't need to anything except pass your QObject to the parent arg of QObject derived objects. Read the docs on QObject, it will explain it far better than that effort... – cmannett85 Jan 06 '12 at 00:27