How a submenu item trigger a Qaction when clicked
-
Hi there ! We currently have 2 sub menu items:
- 'Open...' action
- 'Recent files' action. Which is added to the menu as a QActionList.
I want to merge these two entries as depicted in the below picture. Hovering the mouse on the 'Open...' submenu should open the submenu containing the recent files. Clicking the 'Open...' submenu should trigger the Open... action.
I'm trying to implement that as a QActionList, but the menu 'Open...' is not selectable, clicking it only opens the submenu. Any idea how to do it? Thanks !
-
There's no built-in way to do that, you'd have to implement that yourself.
One way to do it: Subclass your "File"
QMenu
and overridemouseReleaseEvent
or install an event filter on the existing menu, whichever is more convenient. In the handler get action at the release point withQMenu::actionAt
, compare it to the "Open"QMenu::menuAction
and if they're the same callQAction::trigger
on that menu's action. Something like this:yourFileMenu->installEventFilter(someObjectofSomeClass); bool SomeClass::eventFilter(QObject* obj, QEvent* evt) { QMenu* menu = qobject_cast<QMenu*>(obj); if (menu && evt->type() == QEvent::MouseButtonRelease) { QAction* action = menu->actionAt(static_cast<QMouseEvent*>(evt)->pos()); if (action && action->isEnabled() && action->menu()) //it's a sub-menu action { action->trigger(); menu->close(); } } return false; }
This should work fine on Windows at least. I'm not sure if you can do that on platforms with native menus outside of the app area. You'll have to check.
-
Hi,
While the idea might sound nice I must say that I would be pretty surprised (and annoyed) that clicking on a menu that has a submenu acts differently than all other menus that have submenus. Just add a top entry that says "Browse..." or something similar with the recent list under but don't change the standard behavior.