Main Content

Define a Context Menu

This example shows how to define a context menu.

When to Use a Context Menu

Context menus are displayed when users right-click the graphics object for which you assign the context menu. Context menus enable you to provide choices to users for interaction with graphics objects.

Program a context menu when you want user to be able to:

  • Choose among specific options by right-clicking a graphics object.

  • Provide an indication of what each option is via the menu label.

  • Produce a specific result without knowing key combinations.

How to Define a Context Menu

  • Create a ContextMenu object by calling the uicontextmenu function with an output argument.

  • Create each menu item using uimenu.

  • Define callbacks for each menu item in the context menu.

  • Parent the individual menu items to the context menu and assign the respective callback.

  • Assign the ContextMenu object to the ContextMenu property of the object for which you are defining the context menu.

function cm = defineCM
cm = uicontextmenu;
uimenu(cm,"Text","Wider","MenuSelectedFcn",@increaseLW);
uimenu(cm,"Text","Inspect","MenuSelectedFcn",@inspectLine);
end

function increaseLW(~,~)
% Increase line width
h = gco;
orgLW = h.LineWidth;
h.LineWidth = orgLW+1;
end

function inspectLine(~,~)
% Open the property inspector
h = gco;
inspect(h)
end

The defineCM function returns the context menu object that it creates. Assign this object to the ContextMenu property of the line objects created by the plot function.

plot(rand(1,5),"ContextMenu",defineCM)

See Also

|

Related Topics