0

I have a QPushButton in a QWidgetAction in a QMenu. When the button is clicked, I want the action to trigger and the menu to close, returning which action was triggered. According to the docs, the widget itself must trigger the action directly.

Here's my code:

QMenu *menu = new QMenu();
QWidgetAction *widgetAction = new QWidgetAction(menu);
QPushButton *button = new QPushButton("Finish");

widgetAction->setDefaultWidget(button);
menu->addAction(widgetAction);

connect(button, SIGNAL(clicked()), widgetAction, SLOT(trigger()));
connect(widgetAction, SIGNAL(triggered()), menu, SLOT(close())); //Menu won't close without this

QAction* selectedAction = menu->exec(mapToGlobal(ui->pushButton->pos()));
if(selectedAction != NULL)
{
    qDebug() << "no output from here";
}

However selectedAction always returns NULL. Regular QAction's added to the menu automatically close the menu and return pointers to themselves. Why doesn't QWidgetAction?

Thanks for your time!

mrg95
  • 2,371
  • 11
  • 46
  • 89
  • `connect(widgetAction, SIGNAL(triggered()), menu, SLOT(close()));` not making any selection in the menu. I would just connect the signal of specific action triggered to the specific slot then. – Alexander V Jan 01 '17 at 18:45
  • @AlexanderVX What? I don't understand – mrg95 Jan 01 '17 at 18:51
  • You should not close the menu like that or you don't get the action from `exec()`. If you still do that do `connect(widgetAction, SIGNAL(triggered()), this, SLOT(myClose()));` and create the slot `MyWidget::myClose() {doSomething(); menu->close();}`. I just cannot answer the question directly but know how to accomplish the task. – Alexander V Jan 01 '17 at 22:23
  • @AlexanderVX I don't want to call a function, I want to return which action was triggered. Like a regular `QAction`. – mrg95 Jan 02 '17 at 03:12
  • The reason I don't want to simply call another function is because I need access to certain top level widgets AND the widget in the menu. So I would like to work within the scope of the menu, like any other QAction. – mrg95 Jan 03 '17 at 10:55
  • I do it like that with assigning the lambda to the action and not even bother of nested widgets: http://stackoverflow.com/questions/19719397/qt-slots-and-c11-lambda – Alexander V Jan 03 '17 at 16:09
  • 1
    I'm not using c++ 11. I'm not looking to operate ON the action. I need to identify the action that was called after exec returns and then interact with variables in that local scope. Simply put, an actual answer to my question.... – mrg95 Jan 04 '17 at 11:09

0 Answers0