Search code examples
matlabfunctioncallbackmatlab-gui

Multiple callbacks in a MATLAB GUI


I am trying to convert a character vector callback to a function handle. However, I am calling multiple callbacks which I assume I could create a cell array with anonymous functions?

Here is the code:

guiel.hPB(2)=uicontrol(guiel.cPanel(2),'Style','PushButton','Units','pixels',...
        'TooltipString',guiel.plotTt,...
        'Position',[cnst.bhspace 3*cnst.bvspace+2*cnst.bheight cnst.bwidth cnst.bheight],...
        'String','Run Simulation','fontsize',10,'FontWeight','Demi',...
        'CallBack','eval(codeblk.CLOSE_MDL_FCN); set(guiel.cPanel(4),''Visible'',''off'');set(guiel.APPWINDOW,''Resize'',''off''); primePlot;',...
        'Enable','off');

What I am trying to do is to write codeblk.CLOSE_MDL_FCN into a function handle and the rest to be anonymous function handles? However, I am not sure how I can do that.

codeblk.CLOSE_MDL_FCN = ['if  ~isempty(find_system(''Name'',vars.simfilename))'...
                     'vars.simtime = str2num(get_param(vars.simfilename,''StopTime''));'...
                     'set(guiel.hSimtime,''String'',num2str(vars.simtime));'...
                     'save_system(vars.simfilename);'...
                     'close_system(vars.simfilename);'...
                     'end'];

Solution

  • The idea when creating a callback using a function handle is that it is a single function to handle everything for when that GUI object is interacted with. Using a cell array callback is for when you need to pass additional data to the function, not for calling multiple functions. Here's how I would suggest you design your button callback:

    guiel.hPB(2) = uicontrol(..., 'CallBack', @callback_hPB2, ...);
    

    And you would then define two nested functions:

    function callback_hPB2(~, ~)
      close_fcn();
      set(guiel.cPanel(4), 'Visible', 'off');
      set(guiel.APPWINDOW, 'Resize', 'off');
      primePlot();
    end
    
    function close_fcn
      if ~isempty(find_system('Name', vars.simfilename))
        vars.simtime = str2num(get_param(vars.simfilename, 'StopTime'));
        set(guiel.hSimtime, 'String', num2str(vars.simtime));
        save_system(vars.simfilename);
        close_system(vars.simfilename);
      end
    end