Multiple actions on right click on label
Solved
General and Desktop
-
Hi.
I am using the following code to right click on a label and see a context menu:
void MainWindow::ShowContextMenu(const QPoint& pos) { QLabel* mylabel = qobject_cast<QLabel*>(sender()); QPoint globalPos = mylabel->mapToGlobal(pos); QMenu myMenu; myMenu.addAction("Hide"); //myMenu.addAction("Highlight"); QAction* selectedItem = myMenu.exec(globalPos); if (selectedItem) { qInfo()<<"Hide works!"; } else{ //nothing chosen } }
This works fine for one item in the menu (Hide). However, if I want to add another item to the menu, how can I do so?
I can add the item using addAction, but not able to understand how to execute some action if it is clicked.
-
@BigBen Just add another action but remember the instances, call exec and check what it returns:
QMenu myMenu; QAction hide("Hide"); QAction highlight("Highlight"); myMenu.addAction(&hide); myMenu.addAction(&highlight); QAction* selectedItem = myMenu.exec(); if (selectedItem == &hide) { qInfo()<<"Hide works!"; } else if (selectedItem == &highlight) { qInfo()<<"Highlight works!"; } else{ //nothing chosen }
-
@BigBen
When you goQMenu::addAction("SomeString")
it creates aQAction
for you, and returns it. AndQMenu::exec()
returns theQAction
which was clicked. So you could check which one is returned and act on it, like:QAction *hideAction = myMenu.addAction("Hide"); QAction *showAction = myMenu.addAction("Show"); QAction* selectedAction = myMenu.exec(globalPos); if (selectedAction == hideAction) qInfo() << "Hide"; else if (selectedAction == showAction) qInfo() << "Show";
Alternatively, when you create the
QAction
s you could attach a slot to itstriggered
signal:connect(hideAction, &QAction::triggered, this, []() { qInfo() << "Hide"; } );