Main Content

ContextMenu

Context menu UI component

  • Context menu UI component

Description

A context menu UI component displays a set of menu items when you right-click a graphics object or UI component. Use the ContextMenu object to modify the appearance and behavior of a context menu after you create it.

Creation

Create a context menu in a figure using the uicontextmenu function.

Properties

expand all

Callbacks

Context menu opening callback function, specified as one of these values:

  • A function handle.

  • A cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • A character vector containing a valid MATLAB® expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback property value as a function handle, cell array, or character vector, see Specify a Callback Function.

This callback function executes when the context menu opens in response to user interaction. You can use this callback function to customize the context menu appearance based on what the user right-clicked.

This callback function can access specific information about the user's interaction with the app. MATLAB passes this information in a ContextMenuOpeningData object as the second argument to your callback function. In App Designer, the argument is named event. You can query the object properties using dot notation. For example, event.ContextObject returns information about which component the user right-clicked to open the context menu.

Note

While you can specify a ContextMenuOpeningFcn callback for any context menu, the ContextMenuOpeningData object in the callback event data is available only when the context menu satisfies both of these conditions:

  • The context menu is associated with a uifigure-based app (such as an app created in App Designer).

  • The context menu is associated with a UI component (as opposed to a graphics object, such as an Axes or Line object), or is associated with a container that contains only UI components.

This table lists the properties of the ContextMenuOpeningData object.

PropertyValue
ContextObjectObject that the app user right-clicked to open the context menu
InteractionInformation

Information about where in the component the app user right-clicked to open the context menu. This information is stored as an object with different properties depending on the value of ContextObject.

For example, if ContextObject is a Table object, then InteractionInformation stores information about which row and column in the table the user right-clicked. For more details on the properties that InteractionInformation can have, see the next table.

SourceContext menu object that executes the callback
EventName'ContextMenuOpening'

This table lists the properties of the InteractionInformation object. The properties depend on which object the app user right-clicked to open the context menu.

ContextObjectInteractionInformation PropertyValue
AnyLocation

Location where the user right-clicked relative to the bottom-left corner of the parent container of the ContextObject, returned as a two-element vector of the form [x y].

The value of x represents the horizontal distance from the left edge of the parent container to the right-click location. The value of y represents the vertical distance from the bottom edge of the parent container to the right-click location. Distances are measured in pixels.

ScreenLocation

Location where the user right-clicked relative to the bottom-left corner of their primary display, returned as a two-element vector of the form [x y].

The value of x represents the horizontal distance from the left edge of the display to the right-click location. The value of y represents the vertical distance from the bottom edge of the display to the right-click location. Distances are measured in pixels.

TableDisplayRow

Row that the user right-clicked as it appears visually in the table, returned as a numeric scalar.

If the user has not sorted the table, then DisplayRow has the same value as Row. If the user right-clicked an area of the table UI component that is not associated with a row, then DisplayRow is an empty array.

DisplayColumn

Column that the user right-clicked as it appears visually in the table, returned as a numeric scalar.

If the user has not rearranged the table, then DisplayColumn has the same value as Column. If the user right-clicked an area of the table UI component that is not associated with a column, then DisplayColumn is an empty array.

Row

Row that the user right-clicked as it corresponds to the original table data, returned as a numeric scalar.

If the user has not sorted the table, then Row has the same value as DisplayRow. If the user right-clicked an area of the table UI component that is not associated with a row, then Row is an empty array.

Column

Column that the user right-clicked as it corresponds to the original table data, returned as a numeric scalar.

If the user has not rearranged the table, then Column has the same value as DisplayColumn. If the user right-clicked an area of the table UI component that is not associated with a column, then Column is an empty array.

RowHeaderWhether the user right-clicked the table row header, returned as a logical 0 (false) or 1 (true).
ColumnHeaderWhether the user right-clicked the table column header, returned as a logical 0 (false) or 1 (true).
TreeNode

Right-clicked node, returned as a TreeNode object.

If the user right-clicked an area of the tree that is not associated with a node, then Node is an empty array.

Level

Level of the right-clicked node, returned as a numeric scalar. Nodes parented directly to the Tree object are at level 1, nodes parented to a node at level 1 are at level 2, and so on.

If the user right-clicked an area of the tree that is not associated with a node, then Level is an empty array.

ListBoxItem

Index of the right-clicked list box item, returned as a numeric scalar.

If the user right-clicked an area of the list box that is not associated with an item, then Item is an empty array.

Object creation function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Callbacks in App Designer.

This property specifies a callback function to execute when MATLAB creates the object. MATLAB initializes all property values before executing the CreateFcn callback. If you do not specify the CreateFcn property, then MATLAB executes a default creation function.

Setting the CreateFcn property on an existing component has no effect.

If you specify this property as a function handle or cell array, you can access the object that is being created using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Object deletion function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Callbacks in App Designer.

This property specifies a callback function to execute when MATLAB deletes the object. MATLAB executes the DeleteFcn callback before destroying the properties of the object. If you do not specify the DeleteFcn property, then MATLAB executes a default deletion function.

If you specify this property as a function handle or cell array, you can access the object that is being deleted using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Callback Execution Control

Callback interruption, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

This property determines if a running callback can be interrupted. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

MATLAB determines callback interruption behavior whenever it executes a command that processes the callback queue. These commands include drawnow, figure, uifigure, getframe, waitfor, and pause.

If the running callback does not contain one of these commands, then no interruption occurs. MATLAB first finishes executing the running callback, and later executes the interrupting callback.

If the running callback does contain one of these commands, then the Interruptible property of the object that owns the running callback determines if the interruption occurs:

  • If the value of Interruptible is 'off', then no interruption occurs. Instead, the BusyAction property of the object that owns the interrupting callback determines if the interrupting callback is discarded or added to the callback queue.

  • If the value of Interruptible is 'on', then the interruption occurs. The next time MATLAB processes the callback queue, it stops the execution of the running callback and executes the interrupting callback. After the interrupting callback completes, MATLAB then resumes executing the running callback.

Note

Callback interruption and execution behave differently in these situations:

  • If the interrupting callback is a DeleteFcn, CloseRequestFcn, or SizeChangedFcn callback, then the interruption occurs regardless of the Interruptible property value.

  • If the running callback is currently executing the waitfor function, then the interruption occurs regardless of the Interruptible property value.

  • If the interrupting callback is owned by a Timer object, then the callback executes according to schedule regardless of the Interruptible property value.

Note

When an interruption occurs, MATLAB does not save the state of properties or the display. For example, the object returned by the gca or gcf command might change when another callback executes.

Callback queuing, specified as 'queue' or 'cancel'. The BusyAction property determines how MATLAB handles the execution of interrupting callbacks. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

The BusyAction property determines callback queuing behavior only when both of these conditions are met:

  • The running callback contains a command that processes the callback queue, such as drawnow, figure, uifigure, getframe, waitfor, or pause.

  • The value of the Interruptible property of the object that owns the running callback is 'off'.

Under these conditions, the BusyAction property of the object that owns the interrupting callback determines how MATLAB handles the interrupting callback. These are possible values of the BusyAction property:

  • 'queue' — Puts the interrupting callback in a queue to be processed after the running callback finishes execution.

  • 'cancel' — Does not execute the interrupting callback.

This property is read-only.

Deletion status, returned as an on/off logical value of type matlab.lang.OnOffSwitchState.

MATLAB sets the BeingDeleted property to 'on' when the DeleteFcn callback begins execution. The BeingDeleted property remains set to 'on' until the component object no longer exists.

Check the value of the BeingDeleted property to verify that the object is not about to be deleted before querying or modifying it.

Parent/Child

Parent object, specified as a Figure object created with either the uifigure or figure function. If a parent figure is not specified, then MATLAB calls the figure function to create one that serves as the parent.

You can move a ContextMenu object to a different figure by setting this property to the target Figure object.

Context menu children, returned as an empty GraphicsPlaceholder or a vector of Menu objects.

You cannot add or remove children using the Children property. Use this property to view the list of children or to reorder the child menu items. The order of the children in this array reflects the reverse-order of how the menu items appear in an opened context menu.

For example, this code creates three context menus. When you open the context menu in the running app, Menu1 appears as the first menu option.

fig = uifigure;
cm = uicontextmenu(fig);
m1 = uimenu(cm,'Text','Menu1');
m2 = uimenu(cm,'Text','Menu2');
m3 = uimenu(cm,'Text','Menu3');
fig.ContextMenu = cm;
Context menu with three menu items.

cm.Children returns a list of the menu items in the reverse order.

cm.Children
ans = 

  3×1 Menu array:

  Menu    (Menu3)
  Menu    (Menu2)
  Menu    (Menu1)

Objects with the HandleVisibility property set to 'off' are not listed in the Children property.

To add a child to this list, set the Parent property of another Menu object to this ContextMenu object.

Visibility of object handle, specified as 'on', 'callback', or 'off'.

This property controls the visibility of the object in its parent's list of children. When an object is not visible in its parent's list of children, it is not returned by functions that obtain objects by searching the object hierarchy or querying properties. These functions include get, findobj, gca, gcf, gco, newplot, cla, clf, and close. The HandleVisibility property also controls the visibility of the object’s handle in the parent figure's CurrentObject property. Objects are valid even if they are not visible. If you can access an object, you can set and get its properties, and pass it to any function that operates on objects.

HandleVisibility ValueDescription
'on'The object handle is always visible.
'callback'The object handle is visible from within callbacks or functions invoked by callbacks, but not from within functions invoked from the command line. This option blocks access to the object at the command line, but allows callback functions to access it.
'off'The object handle is invisible at all times. This option is useful for preventing unintended changes to the UI by another function. Set the HandleVisibility to 'off' to temporarily hide the handle during the execution of that function.

Identifiers

This property is read-only.

Type of graphics object, returned as 'uicontextmenu'.

Object identifier, specified as a character vector or string scalar. You can specify a unique Tag value to serve as an identifier for an object. When you need access to the object elsewhere in your code, you can use the findobj function to search for the object based on the Tag value.

User data, specified as any array. Specifying UserData can be useful for sharing data within apps. See Share Data Among Callbacks for more information.

Examples

collapse all

Create a context menu that prints a message in the Command Window each time you open it.

Create a line plot in a figure. Then, create a context menu with one menu item and assign it to the line plot. Create a ContextMenuOpeningFcn callback function that displays output in the Command Window each time the context menu opens.

f = figure;
cm = uicontextmenu(f);
m = uimenu(cm,"Text","Menu1");
cm.ContextMenuOpeningFcn = @(src,event)disp("Context menu opened");
p = plot(1:10,"ContextMenu",cm);

To view the context menu, right-click the plot line. When the context menu opens, the Command Window displays Context menu opened.

The context menu with a menu item called "Menu1" displays on the plot line.

Since R2023b

Create an app that displays hyperlinks and allows users to copy the link URLs to the clipboard using a context menu.

In a file named hyperlinkApp.m, write a function that implements the app:

  • Create a UI figure and a grid layout manager to lay out the app.

  • Create two hyperlinks in the grid layout manager.

  • Create a context menu with a Copy Hyperlink menu item, and assign the context menu to both of the hyperlinks.

  • Write a callback function named copyHyperlink. In the callback function, access the right-clicked Hyperlink object by using the event.ContextObject event data, and then copy the URL to the clipboard. Assign the function to the MenuSelectedFcn callback property of the menu item. For more information about callbacks, see Create Callbacks for Apps Created Programmatically.

function hyperlinkApp
fig = uifigure;
g = uigridlayout(fig,[2, 1]);
g.RowHeight = {'fit','fit'};

hlink1 = uihyperlink(g);
hlink1.Text = "MathWorks Home";
hlink1.URL = "https://www.mathworks.com/";
hlink2 = uihyperlink(g);
hlink2.Text = "MATLAB App Building";
hlink2.URL = "https://www.mathworks.com/products/matlab/app-designer.html";

cm = uicontextmenu(fig);
m = uimenu(cm);
m.Text = "Copy Hyperlink";
hlink1.ContextMenu = cm;
hlink2.ContextMenu = cm;

m.MenuSelectedFcn = @copyHyperlink;
end

function copyHyperlink(src,event)
url = event.ContextObject.URL;
clipboard("copy",url)
end

Before R2023b: Write the callback function to access the right-clicked Hyperlink object by querying the CurrentObject property of the figure instead of by using the event.ContextObject event data.

Run the hyperlinkApp function. Right-click one of the hyperlinks, and then select Copy Hyperlink to copy the link URL.

UI figure window with two hyperlink UI components. A context menu with a "Copy Hyperlink" menu item is open and the pointer is pointing to the menu item.

Since R2023b

Create an app that displays a table and allows users to delete rows by using a context menu item. Program the context menu item to appear only when a user right-clicks a row of table data.

In a file named tableApp.m, write a function that implements the app:

  • Create a UI figure and a table UI component with some random data.

  • Create a context menu with a Delete Row menu item, and assign the context menu to the table.

  • Write two callback functions to respond to context menu actions:

    • deleteRow — Query the row of the table that was right-clicked, and then delete that row.

    • toggleVisibility — Show the Delete Row menu item when the user right-clicks a row of table data, and hide the item otherwise.

    In each callback, use the event.InteractionInformation callback event data to access information about where in the table the user right-clicked to open the context menu.

  • Assign the deleteRow function to the MenuSelectedFcn callback property of the menu item, and assign the toggleVisibility function to the ContextMenuOpeningFcn callback property of the context menu. For more information about callbacks, see Create Callbacks for Apps Created Programmatically.

function tableApp
fig = uifigure;
tbl = uitable(fig);
tbl.Position = [20 20 400 300];
tbl.Data = randi(10,[10 4]);

cm = uicontextmenu(fig);
m = uimenu(cm);
m.Text = "Delete Row";
tbl.ContextMenu = cm;

m.MenuSelectedFcn = @deleteRow;
cm.ContextMenuOpeningFcn = @(src,event)toggleVisibility(src,event,m);
end

function deleteRow(src,event)
tbl = event.ContextObject;
row = event.InteractionInformation.Row;
tbl.Data(row,:) = [];
end

function toggleVisibility(src,event,m)
row = event.InteractionInformation.Row;
rowClicked = ~isempty(row);
m.Visible = rowClicked;
end

Run the tableApp function and right-click the table. The context menu appears only when you right-click a table row. Select the Delete Row item to delete the right-clicked row.

UI figure window with a table. A context menu with a "Delete Row" item is visible over a table row header and the pointer is pointing to the menu item.

The specific callback event data stored in the event.InteractionInformation property depends on the UI component that the user right-clicked to open the context menu. For more information, see the callback property descriptions on Menu and ContextMenu.

Since R2023b

Create a context menu for a tree component. Customize the context menu action based on the level of the tree node that the user right-clicks.

In a new script in your current folder, create a UI figure. Then, create a tree with four top-level nodes and a set of nested nodes.

fig = uifigure;

t = uitree(fig,"Position",[20 200 175 100]);

category1 = uitreenode(t,"Text","Runners");
r1 = uitreenode(category1,"Text","Joe");
r2 = uitreenode(category1,"Text","Linda");

category2 = uitreenode(t,"Text","Cyclists");
c1 = uitreenode(category2,"Text","Rajeev");

category3 = uitreenode(t,"Text","Hikers");
h1 = uitreenode(category3,"Text","Jack");

category4 = uitreenode(t,"Text","Swimmers");
s1 = uitreenode(category4,"Text","Logan");

UI figure window with a tree that has four collapsed top-level nodes

Create a context menu with one menu item and two submenus that users can click to expand a single tree node or all of the tree nodes. For each submenu, specify a MenuSelectedFcn callback function to execute when a user selects the menu option.

cm = uicontextmenu(fig);
m1 = uimenu(cm,"Text","Expand...");

sbm1 = uimenu(m1,"Text","This Node", ...
    "MenuSelectedFcn",@expandSingle);
sbm2 = uimenu(m1,"Text","All Nodes", ...
    "MenuSelectedFcn",@expandAll);

Assign the context menu to the top-level tree nodes by setting the ContextMenu property of each node to the ContextMenu object.

category1.ContextMenu = cm;
category2.ContextMenu = cm;
category3.ContextMenu = cm;
category4.ContextMenu = cm;

At the bottom of the file, define the expandSingle and expandAll callback functions. Define the functions to accept the source and event data that MATLAB passes to all callback functions. Use the event.InteractionInformation and event.ContextObject properties to access information about where the user right-clicked to open the context menu.

function expandSingle(src,event)
node = event.InteractionInformation.Node;
expand(node)
end

function expandAll(src,event,t)
n = event.ContextObject;
t = ancestor(n,"uitree");
expand(t)
end

Save and run the script. Right-click any of the top-level tree nodes to view the context menu.

UI figure window with a tree that has four collapsed top-level nodes. Over the "Cyclists" node, a context menu with an "Expand" menu item and two submenu items, "This Node" and "All Nodes", is visible. The pointer is pointing to the "All Nodes" item.

Version History

Introduced before R2006a

expand all