Simple detail overlooked in the legend ItemHitFcn callback documentation.
- 'alt' — Single-click right mouse button, both mouse buttons (Windows and Mac), or middle mouse button (Mac and Linux). If the ContextMenu property contains a valid context menu (which is the default), then this type of click opens the context menu instead of triggering the ItemHitFcn callback.
Setting the ContextMenu property equal to an empty array value allows the ItemHitFcn to behave as anticipated on right mouse button use.
% Setup test plot with legend
x = linspace(0,10);
y1 = sin(x); y2 = cos(x); y3 = sin(x)+cos(x); y4 = sin(x).*cos(x);
hFig = figure;
plot(x,y1,x,y2,x,y3,x,y4)
hLeg = legend('Line 1','Line 2','Line 3','Line 4');
% Assign callback function
hLeg.ItemHitFcn = @LineVisible;
hLeg.ContextMenu = [];
% or
% set(hLeg,'ItemHitFcn',@LineVisible,'ContextMenu',[])
Code for toggling line visibility with left mouse button and opening a context menu for line deletion.
function LineVisible(src, event)
%LINEVISIBLE toggles visibility of lines in plots by selecting from legend
%or delete unwanted items.
% Determine which mouse button was used to activate the ItemHitFcn callback
% for the legend
if strcmp(event.SelectionType,'normal')
% Checks the current visibility setting of the source plot line and
% switches to the opposite state
if strcmp(event.Peer.Visible,'on')
event.Peer.Visible = 'off';
else
event.Peer.Visible = 'on';
end
elseif strcmp(event.SelectionType,'alt')
% Creates a context menu, which will be initiated immediately after
% this function completes execution
hCM = uicontextmenu(gcf);
uimenu(hCM,'Text','Delete Item','MenuSelectedFcn',{@DeleteItem,event});
src.ContextMenu = hCM;
end
end
%%
function DeleteItem(~, ~, hItem)
% Deletes the target item & resets the legend's ContextMenu property
delete(hItem.Peer)
hItem.Source.ContextMenu = [];
end