我已将 uicontextmenu
添加到线对象。 uicontextmenu
包含 3 个复选框。每当我检查其中任何一个时,uicontextmenu
都会消失。我希望 uicontextmenu
可见一段时间,以便我可以选中多个框并查看更改(与按钮组相同,但在 uicontextmenu
中)。有没有解决这个或其他方法的方法?
cmenu=uicontextmenu;
set(he,'uicontextmenu',cmenu);
item1=uimenu(cmenu,'label','Data A','checked','off','callback',@func_a);
item2=uimenu(cmenu,'label','Data B','checked','off','callback',@func_b);
item3=uimenu(cmenu,'label','Data C','checked','off','callback',@func_c);
基本上,he
是由plot(x,y)
创建的线对象,func_a、func_b、func_c
是转换属性的函数'checked'
到 on|off
。
最佳答案
此示例很大程度上受到了 Benoit_11 解决方案的启发,但有所改进。我还觉得你的回调中的 3 个不同的函数在做不同的事情,所以我让 3 个不同的菜单改变了行的不同属性(而不是用不同的值改变相同的属性)。
我在一个嵌套函数中创建了 uimenu 回调。它根据 uimenu 定义中提供的参数 what2do
决定要做什么(但可以保留 3 个独立的函数)。但是,请注意,切换复选标记的功能对于所有 uimenu 都是相同的(您不需要为每个单独的功能)。
function hf = TestUiContext2
%// Extension of Benoit_11 solution
clear ; clc ; close all
hf = figure ; %// return the handle of the figure
hax = axes; %// Create axes and save handle
plot(rand(20,3)); %// Plot three lines
hcmenu = uicontextmenu; %// Define a context menu; it is not attached to anything
%// Define the context menu items and install their callbacks
item1 = uimenu(hcmenu, 'Label','Bold line' , 'Callback' , {@uiCallback,'bold'} );
item2 = uimenu(hcmenu, 'Label','Dotted line' , 'Callback' , {@uiCallback,'dots'} );
item3 = uimenu(hcmenu, 'Label','Markers on' , 'Callback' , {@uiCallback,'mark'} );
hlines = findall(hax,'Type','line'); %// Locate line objects
for line = 1:length(hlines) %// Attach the context menu to each line
set(hlines(line),'uicontextmenu',hcmenu)
end
function uiCallback(obj,~,what2do)
hline = gco ;
switch what2do
case 'bold'
toggle_bold_line(hline)
case 'dots'
toggle_dotted_line(hline)
case 'mark'
toggle_markers(hline)
end
%// reposition the context menu and make it visible
set(hcmenu,'Position',get(gcf,'CurrentPoint'),'Visible','on')
toggle_checkmark(obj) %// toggle the checkmark
end
function toggle_checkmark(obj)
if strcmp(get(obj,'Checked'),'on')
set(obj,'Checked','off')
else
set(obj,'Checked','on')
end
end
function toggle_bold_line(hline)
if get(hline,'LineWidth')==0.5
set(hline,'LineWidth',2)
else
set(hline,'LineWidth',0.5)
end
end
function toggle_dotted_line(hline)
if strcmpi(get(hline,'LineStyle'),':')
set(hline,'LineStyle','-')
else
set(hline,'LineStyle',':')
end
end
function toggle_markers(hline)
if strcmpi(get(hline,'Marker'),'none')
set(hline,'Marker','o')
else
set(hline,'Marker','none')
end
end
end
现在您可以享受一次性勾选所有菜单的乐趣;)
关于matlab - 如何防止uimenu(MATLAB)在选中时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27909271/