How to pass a function pointer to a method so that it can be used in Qt's connect()?

538 Views Asked by At

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()).

1

There are 1 best solutions below

3
On
auto *subMenu = builder.createMenu(SECTION, this, SLOT(TextEdit::onInsertChars()));

The above should be:

auto *subMenu = builder.createMenu(SECTION, pointerToTheTextEdit, SLOT(onInsertChars()));

(of course if the onInsertChars() method is a slot in the class whose method is making the above call, then you can pass this as the pointer to the object that has the onInsertChars() slot)

Also, you may want to rename const char * slot in your createMenu() function to something else, as Qt's MOC preprocessor has kind of claimed the word slot 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 to const char * slotName or something instead.