PDA

View Full Version : Mapping menu actions to handlers



xtal256
24th August 2010, 00:57
This is sort of a Qt specific question, but mainly i am just having trouble with the design of my menu system. I want to have context menus on items in a tree view, where each menu item (QAction to be more specific) may operate on the object that tree item represents or on the item itself. For example, one action is to recursively expand all sub items of the selected item, whereas another action is to view the properties of the object.

If there were only one menu then that would be fine. I'd just connect the signals to slots like you normally would. But i also want to use context menus elsewhere, such as in a list of objects in the search results dialog. The menu here should also have actions on the selected object, but it would not make sense to have the "expand all" action because this list is not a tree. But instead, another useful action would be to locate and highlight that object in the tree view (which is on my main window).

So the problem is that i don't want duplicate code to handle the action events everywhere i use a context menu. And sometimes i may not even use a menu but would have buttons on a toolbar (which also use QActions). Yet i need to have actions specific to each menu/toolbar.

I tried to make an ActionManager class which has a function for each action and has a mapping of QActions to function pointers so that i can call the appropriate function when the menu item is selected. But i realized that wouldn't work for the "expand all" action since it would need a reference to the tree item. I need to use some sort of signal/slot mechanism, possible QSignalMapper, but i am not sure how.

The source code in question is spread out over numerous classes and it's hard to pull out the code specific to this question. I have uploaded my source at SourceForge, here (http://windowdetective.sourceforge.net/Window%20Detective/src/).
The main classes in question are:
/ui/ActionManager.h (http://windowdetective.sourceforge.net/Window%20Detective/src/ui/ActionManager.h) (and .cpp)
/ui/MainWindow.h (http://windowdetective.sourceforge.net/Window%20Detective/src/ui/MainWindow.h) (and .cpp)
/ui/custom_widgets/WindowTree.h (http://windowdetective.sourceforge.net/Window%20Detective/src/ui/custom_widgets/WindowTree.h) (and .cpp)

The WindowTree widget is used both as a tree view in the main window and also as a list (just a tree with no child nodes) in the search results window. These two uses need menus which have mostly the same actions (on the actual object the tree/list holds) but have some different actions.


Any help would be appreciated. thanks

xtal256
25th August 2010, 08:41
anyone?
I'm really stuck on this one. If i cannot think of any better way, i guess i will have to use duplicate code for handling most of my menu actions.