uicontextmenu

Create context menu

Syntax

h = uicontextmenu
h = uicontextmenu(Name,Value,...)
h = uicontextmenu(f)
h = uicontextmenu(f,Name,Value,...)

Description

h = uicontextmenu creates a context menu in the current figure and returns the uicontextmenu object in the variable, h. A context menu is a menu that appears when the user right-clicks on a graphics object.

h = uicontextmenu(Name,Value,...) specifies one or more uicontextmenu property names and corresponding values. Use this syntax to override the default uicontextmenu property values.

h = uicontextmenu(f) designates a specific figure, f, to be the parent of the uicontextmenu.

h = uicontextmenu(f,Name,Value,...) designates a specific parent figure and specifies one or more uicontextmenu properties.

Initially, the uicontextmenu has no menu items. To create a menu item, call the uimenu function to create a uimenu. Set the uimenu's Parent property to be the uicontextmenu object. The menu items appear in the order in which the uimenu statements appear. However, you can change the order by changing the order of the elements in the uicontextmenu's Children property. To make the context menu appear when the user right-clicks on a specific object, set that object's UIContextMenu property to be the uicontextmenu object.

Examples

This code creates a context menu that appears when the user right-clicks on a plotted line. The menu items enable you to change the line style.

% Create axes and save handle
hax = axes;
% Plot three lines
plot(rand(20,3));
% Define a context menu; it is not attached to anything
hcmenu = uicontextmenu;
% Define callbacks for context menu 
% items that change linestyle
hcb1 = ['set(gco,''LineStyle'',''--'')'];
hcb2 = ['set(gco,''LineStyle'','':'')'];
hcb3 = ['set(gco,''LineStyle'',''-'')'];
% Define the context menu items and install their callbacks
item1 = uimenu(hcmenu,'Label','dashed','Callback',hcb1);
item2 = uimenu(hcmenu,'Label','dotted','Callback',hcb2);
item3 = uimenu(hcmenu,'Label','solid','Callback',hcb3);
% Locate line objects
hlines = findall(hax,'Type','line');
% Attach the context menu to each line
for line = 1:length(hlines)
    set(hlines(line),'uicontextmenu',hcmenu)
end

Was this topic helpful?