Legend ItemHitFcn with multiple functionality using left- and right-mouse buttons
Show older comments
I use the legend ItemHitFcn frequently to toggle visiblity of specific lines, but would like to add a context menu to the legend that would allow the user to delete the selected plot item. Per the online help documentation for legend properties, it seems that the ItemHitFcn property has the ability to do this, but it not clear to me how to implement this in the code.
Ideally, the user would be able to toggle visibility with the left mouse button and open the context menu with the right mouse button (able to get this far) to delete the target (failing thus far).
I would guess that it has to do with how I have been trying to assign the context menu. Sample section of my code are provided below.
Function to toggle visibilty:
function LineVisible(~, event)
%LINEVISIBLE toggles visibility of lines in plots by selecting from legend.
% % Rough example of adding item deletion code
% if strcmp(event.SelectionType,"alt")
% delete(event.Peer)
% return
% end
% 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
end
Generic plot with assignment of LineVisible to the legend ItemHitFcn.
% Plot setup with ItemHitFcn assignment for line visibilty
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');
hLeg.ItemHitFcn = @LineVisible;
Creating the context menu and assigning to the ItemHitFcn
%% Initialize context menu object
hCM = uicontextmenu(hFig);
%% Create context menu item that will call the legend's ItemHitFcn
% Tries to assign as context menu's ItemHitFcn, which does not exist
m1 = uimenu(hCM,"Text","Delete Item","MenuSelectedFcn",@ItemHitFcn);
% No apparent effect when menu item is selected.
m2 = uimenu(hCM,"Text","Delete Item");
% Calls @LineVisible, but does not use ItemHitFcn to indicate the Peer
% object for deletion
m3 = uimenu(hCM,"Text","Delete Item","MenuSelectedFcn",@LineVisible);
% Error using @(hLeg)ItemHitFcn(hLeg)
m4 = uimenu(hCM,"Text","Delete Item","MenuSelectedFcn",@(hLeg)ItemHitFcn(hLeg));
%% Assgin object to legend ContextMenu property
hLeg.ContextMenu = hCM;
Accepted Answer
More Answers (0)
Categories
Find more on Graphics Object Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!