Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-parenting GUI Objects

Tags:

matlab

How can I transfer GUI objects (buttons, sliders, lists, etc...) back and forth between 2 figures, while maintaining their functionality (callbacks and interactions)? In other words, transfer all the objects from figure 1 to figure 2, and have them execute their scripts as they have on figure 1.

like image 592
Yuval Weissler Avatar asked Nov 09 '22 07:11

Yuval Weissler


1 Answers

The trick here is to manage how you set up your uicontrols and your callbacks work, and to use the legacy switch in copyobj as "un"documented here

The example below allows you to reparent a copy of all your objects from figure to figure - I appreciate this is not "transferring" but copying -> but they all still work independently...

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
like image 180
matlabgui Avatar answered Nov 15 '22 09:11

matlabgui