[Qt-interest] How does one dynamically modify a menu?

Andre Somers andre at familiesomers.nl
Tue Feb 8 11:37:34 CET 2011


Op Di, 8 februari, 2011 11:11 am, schreef Oliver.Knoll at comit.ch:
> (...)
> So I understand you want to be able to show two completely different menu
> contents attached to the same top-level menu entry, and no (or just very
> few) menu entries (QAction) "overlap".
>
> You could still create ONE QMenu, add ALL QActions, and set the visibility
> of those QActions accordingly, depending on your application state.
>
> Or you really instantiate two distinct QMenu instances (if those menus
> really don't contain the same functionality) and add both to the menu bar
> with http://doc.qt.nokia.com/latest/qmenubar.html#addMenu. Then you switch
> the visibility on the entire QMenu instead of on the single QActions, that
> should work, too.

If the case is as stated above: two menu's with the same name, but to a
large extend different contents, I'd go for the second approach. *Much*
easier to maintain, I think. Instead of having to toggle the visibility of
a large host of actions, you only need to toggle the visibility two menus.
That means you also can not forget to add a menu item to the code that
manages the visibility if you decide to add a menu item later on.

However, also check QActionGroup. You can add QActions to a QActionGroup,
managing their visibility and other properties together. This would allow
you to do the following:
Create a single menu to which you add all actions: 1) the actions that are
always available, 2) the actions that are only available in state A, and
3) the actions that are only available in state B. Now, add the actions
under 2) to one QActionGroup, and those under 3) to another QActionGroup.
You can now manipulate the contents of your menu by just toggeling the
visibility of these action groups based on the state of your application.

Perhaps the above would be the most elegant solution.

André





More information about the Qt-interest-old mailing list