如何在两个数字之间来回传输GUI对象(按钮,滑块,列表等等),同时保持其功能(回调和交互)?换句话说,将所有对象从图1转移到图2,然后让它们像图1中那样执行脚本。
答案 0 :(得分:1)
这里的诀窍是管理您设置uicontrols和回调的工作方式,并将copyobj中的旧版开关用作"un"documented here
以下示例允许您从图中重新显示所有对象的副本 - 我很欣赏这不是"转移"但复制 - >但他们仍然独立工作......
function test_reparentObjects
% Create a new figure
f1 = figure ( 'Name', 'Original Figure' );
% Create some objects - make sure they ALL have UNIQUE tags - this is important!!
axes ( 'parent', f1, 'tag', 'ax' );
uicontrol ( 'style', 'pushbutton', 'position', [0 0 100 25], 'string', 'plot', 'parent', f1, 'callback', {@pb_cb}, 'tag', 'pb' );
uicontrol ( 'style', 'pushbutton', 'position', [100 0 100 25], 'string', 'reparent', 'parent', f1, 'callback', {@reparent}, 'tag', 'reparent' );
uicontrol ( 'style', 'text', 'position', [300 0 100 25], 'string', 'no peaks', 'parent', f1, 'tag', 'txt' );
uicontrol ( 'style', 'edit', 'position', [400 0 100 25], 'string', '50', 'parent', f1, 'callback', {@pb_cb}, 'tag', 'edit' );
end
function pb_cb(obj,event)
% This is a callback for the plot button being pushed
% find the parent figure
h = ancestor ( obj, 'figure' );
% from the figure find the axes and the edit box
ax = findobj ( h, 'tag', 'ax' );
edt = findobj ( h, 'tag', 'edit' );
% convert the string to a double
nPeaks = str2double ( get ( edt, 'string' ) );
% do the plotting
cla(ax)
[X,Y,Z] = peaks(nPeaks);
surf(X,Y,Z);
end
function reparent(obj,event)
% This is a callback for reparenting all the objects
currentParent = ancestor ( obj, 'figure' );
% copy all the objects -> using the "legacy" switch (r2014b onwards)
% this ensures that all callbacks are retained
children = copyobj ( currentParent.Children, currentParent, 'legacy' );
% create a new figure
f = figure ( 'Name', sprintf ( 'Copy of %s', currentParent.Name ) );
% reparent all the objects that have been copied
for ii=1:length(children)
children(ii).Parent = f;
end
end