Example code here, followed by description.
F = uifigure(HandleVisibility="on");
L = uigridlayout(F,[1 2]);
function createModuleInMyApp(k)
cm = uicontextmenu(F,UserData="n° "+k);
uitreenode(tree, Text=""+text+k, UserData="n° "+k);
uimenu(cm,Text="print me",UserData="n° "+k,Accelerator='F',MenuSelectedFcn={@example, k});
function example(src, ~, varargin)
disp("user selected object")
disp("object that is executing callback")
disp("id of context menu: "+src.UserData)
disp("associated data with callback k: "+varargin{1})
Context: I have a group of tools that work independently, and the task is to integrate their respective user interfaces in a modular way — depending on the user needs, modules should be added or removed within a single uifigure.
The individual user interfaces are sometimes equipped with uicontextmenu: buttons/menus/uicontrols are the targets of the uicontextmenu, and indeed the menu only opens and options are shown when the user right-clicks on the correct component, not anywhere on the figure. However, the parent of the uicontextmenu is still the uifigure — so when the interfaces are combined, the general figure accumulates all the uicontextmenu elements. Sometimes, multiple uicontextmenu options share the same shortcuts — for instance, (Ctrl+F) performs one action for one module and something else for another. The callbacks are numerous and varied, so we would prefer to maintain the configuration with multiple uicontextmenu instead of merging them all into one — the tools might be in separate repositories, and keeping the code isolated is the preferred approach when it comes to making changes to individual modules.
Note: the modules within a single uifigure work correctly when using the mouse — right-clicking. I assume that this way, MATLAB forces the figure to access the uicontextmenu assigned to the component.
Problem: The malfunction occurs when, after selecting a certain component, for example a uitreenode, a keyboard shortcut is performed. In my current situation, and from what I understand from the example I'm sharing, the shortcut is not detected by the uicontextmenu associated with the selected object, but rather by the first uicontextmenu found in uifigure.Children. As a result, it carries incorrect information and performs actions targeting the wrong component.
Not a valid Solution: If I reorder the accumulated uicontextmenu elements in the uifigure, I would be able to match the situation I care about. However, there's a problem — reordering the children of the uifigure triggers a graphical refresh of the entire app (and presumably an internal rehash of callbacks), which resets the interface aesthetics (e.g., collapses all uitree nodes, clears text boxes), making the user experience frustrating.
Question: Is there something I haven't considered? Are there alternative solutions?