Background: I want to dynamically create the structure of a context menu and pass the slot of the action items to the method that creates the context menu.
The actual slot is in a QWidget class. I have tried different solutions by passing a function pointer. But they don't compile. Typical error message: "cannot initialize a parameter of type 'void (*)()' with an rvalue of type 'void (TextEdit::*)()'"
This compiles, but does not trigger the desired event:
MenuBuilder builder(&parentMenu);
auto *subMenu = builder.createMenu(SECTION, this, SLOT(TextEdit::onInsertChars()));
And the corresponding method:
QMenu *MenuBuilder::createMenu(const MenuDescription &menuDescription,
const QObject *receiver, const char *target) {
...
inlineMenu->addAction(text, receiver, target);
...
}
I'm sure there's an obvious solution, but I can't figure it out.
The solution: In this context you have to pass SLOT(onInsertChars())
instead of SLOT(TextEdit::onInsertChars())
.
The above should be:
(of course if the
onInsertChars()
method is a slot in the class whose method is making the above call, then you can passthis
as the pointer to the object that has theonInsertChars()
slot)Also, you may want to rename
const char * slot
in yourcreateMenu()
function to something else, as Qt's MOC preprocessor has kind of claimed the wordslot
for its own purposes and that might cause problems for you if you try to use it as a parameter name. Maybe rename the parameter toconst char * slotName
or something instead.