0

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

BodyFit
  • 1
  • 1

1 Answers1

0
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.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • Thanks for the quick reply. "this" is indeed the pointer to the object that contains the method onInsertChars(). To be on the safe side, I renamed the parameter "slot". But unfortunately that wasn't the solution. – BodyFit Dec 12 '19 at 23:35
  • Be sure to check your program's stdout/stderr output. Usually when Qt fails to connect up a signal/slot connection, it will print a warning message there describing why it couldn't do it. – Jeremy Friesner Dec 13 '19 at 00:23
  • Yeah, you gave me the crucial hint! Everything is set correctly, but I was too busy with the compiler errors to pay attention to the stderror output, which states: "QObject::connect: No such slot TextEdit::TextEdit::onInsertChars()". Instead of SLOT(TextEdit::onInsertChars()) I have to pass SLOT(onInsertChars()). – BodyFit Dec 13 '19 at 13:14