MATLAB Answers

Why is the parent of a uicontextmenu object always the top level figure?

12 views (last 30 days)
J. Alex Lee
J. Alex Lee on 12 Jan 2016
Edited: Greg on 6 Dec 2017
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:
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) ...
% OUTPUTS: Querying the parents
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...


Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 12 Jan 2016
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.


J. Alex Lee
J. Alex Lee on 12 Jan 2016
Thanks, I realized I didn't actually try to set the parent of the contextmenu object in those examples, and also confused the parent of the uimenu items with the parent of the uicontext menu.
Still, is there a way to access the "parent object" with which a particular uicontextmenu object is associated, without having to pass its handle to the callback via arguments or UserData properties?
Greg on 6 Dec 2017
EDIT: Sorry, just read the last line "without having to pass its handle ..."
I know the thread is almost fully 2 years old, but for anybody still curious:
When you define your uimenu, add a callback. You can pass extra inputs at the callback declaration stage:
uimenu(ax.UIContextMenu,'Label','Axes Menu Label', ...
Note that "ax" is your third input to mycontextfcn because of some magic MATLAB uses in defining callbacks this way. The @mycontextfcn syntax automatically gives you hObject and eventdata as the first 2 inputs.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Translated by