M
M
Mercury132016-05-24 14:20:50
Qt
Mercury13, 2016-05-24 14:20:50

Qt: who owns createStandardContextMenu() and how to destroy it?

Here is the code that crashes if you call the same acAddNote (which, in turn, calls the modal dialog).

QSharedPointer<QMenu> menu { tableDelegate.editor()->createStandardContextMenu() };
    menu->addSeparator();
    acAddNote->setText(STR_ADDNOTE);
    menu->addAction(acAddNote);
    menu->exec(tableDelegate.editor()->mapToGlobal(point));

The code is called from a slot bound to QLineEdit::customContextMenuRequested. And QLineEdit is an editor in a table; Here we have a duck in a hare. Of course, somewhere in the middle of the exec, the editor disappears, possibly taking some of the objects with it.
If instead of QSharedPointer we put a simple QMenu* pointer, it's all right, but doesn't the memory “flow”?
The documentation says that "The popup menu's ownership is transferred to the caller". I'm always being approached to interpret the rules of board games, but I can't interpret this - in my opinion, whoever caused it destroys it.
What to do? Who owns this menu and how to destroy it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-05-24
@Mercury13

The Qt sources say: the owner is the editor.

02405 #endif
02406     d->actions[QLineEditPrivate::ClearAct]->setEnabled(!d->readOnly && !d->text.isEmpty() && d->hasSelectedText());
02407     d->actions[QLineEditPrivate::SelectAllAct]->setEnabled(!d->text.isEmpty() && !d->allSelected());
02408 
02409     QMenu *popup = new QMenu(this);
02410     popup->setObjectName(QLatin1String("qt_edit_menu"));
02411     popup->addAction(d->actions[QLineEditPrivate::UndoAct]);
02412     popup->addAction(d->actions[QLineEditPrivate::RedoAct]);
02413     popup->addSeparator();

Well, of course. Although the signal-slot mechanism turned out to be the cause - its initiator disappeared during signal processing! Let me briefly explain what I had to do.
1. Out of harm's way, the action created a new one each time, the owner created the menu.
2. As soon as the action is called, the ownership of the menu is transferred to another location.
3. After exec() the menu is destroyed without any conditions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question