Search code examples
matlabmatlab-gui

Error using delete() MATLAB GUI


I get the error like this when I pressed 'X' to close the popup window.

Here is the error I get:

Undefined function or variable 'PopupWindow'.

Error while evaluating UIControl Callback

Here is the code I use:

function PopupWindow = alertBox(figg,position,showtext,titlebar);

    PopupWindow = uipanel('Parent',figg,'Units','pixels','Position',position,...
            'BackGroundColor',CYAN,'BorderType','beveledout','ButtonDownFcn','','Visible','on');

    uicontrol('Parent',PopupWindow,'Units','pixels','Style','PushButton','String','X',...
                    'Position',[position(3)-margin+1 position(4)-margin+1 margin-2 margin-2],'Callback',...
                    ['delete(PopupWindow);']); 

Solution

  • You have defined your callback as a character vector, which MATLAB evaluates in the base workspace where PopupWindow is not defined. You can instead use an anonymous function as your callback.

    For example:

    fig = figure();
    a = uicontrol('Parent', fig, 'Style', 'Pushbutton', 'Units', 'Normalized', ...
                  'Position', [0.1 0.1 0.8 0.8], 'String', 'Delete Figure', ...
                  'Callback', @(h,e)delete(fig));
    

    Gives us a figure window that will close when the button is clicked:

    yay

    Note that I've defined the anonymous function to accept & throw away two inputs. This is because graphics object callbacks accept 2 inputs by default, the handle of the object whose callback is executing and the event data structure. In this simple case we won't need either one, but there are many situations where this information would be retained (e.g. the event data for a button press callback).