MATLAB: Is the parent of a uicontextmenu object always the top level figure

uicontextmenu

The uicontextmenu() function is supposed to take a parent handle as input, but when querying a resultant's object's parent, I always get the top level figure. What am I missing?
Example to illustrate:
MATLAB code
clc;
close all;
%




hFig = figure;
ax = axes;
hXLab = xlabel(ax,'XLABELSTRING');
%
%
hFig.UIContextMenu = uicontextmenu;
ax.UIContextMenu = uicontextmenu;
hXLab.UIContextMenu = uicontextmenu;
%
for i = 1:4
uimenu(hFig.UIContextMenu , 'Label',...
sprintf('fig item %d',i) ...
);
uimenu(ax.UIContextMenu , 'Label',...
sprintf('ax item %d',i) ...
);
uimenu(hXLab.UIContextMenu , 'Label',...
sprintf('xLabel item %d',i) ...
);
end
%
% OUTPUTS: Querying the parents
%
hFig.UIContextMenu.Parent
ax.UIContextMenu.Parent
hXLab.UIContextMenu.Parent
I would expect the first line to return the figure handle, the second line to return the axes handle, and the third line to return the axis label handle, but they all return the figure handle.
Why I want to do this: if there are multiple axes in my GUI, it would be nice to write a general purpose callback for a uicontextmenu object associated with an axes to operate on its parent axes.
One way I can think of to achieve this is to hard-code the intended parent's handle into the uicontextmenu object's UserData property, but that seems inelegant…

Best Answer

UICONTEXTMENU objects are children of the parent figure. The allowed value for the parent input is a figure handle as stated in the documentation for the function itself as well as in the entry for the Parent property on the documentation page listing the uicontextmenu properties.
You associate them with a particular graphics object by setting the graphics object's UIContextMenu property to contain the uicontextmenu object, as shown in the examples on the function documentation page.