MATLAB: How to make the GUI wait until a specific task is executed before resuming

guiguideMATLABwaitwaitfor

How do I make my GUI wait until a specific task is executed before resuming?
I am trying to create an interactive GUI that requests information from the user and then passes the value to VARARGOUT. I would like to have the value passed only after the user chooses to close the GUI by clicking on the 'Close' button.

Best Answer

One method for doing this is to use the WAITFOR function and have the code wait for a particular property of a particular graphics handle to change.
In the following example, the GUI has a popup menu and a 'Close' button. The GUI is called by passing in a number.
a = SelectValue(3);
This number is used to set the value of the popup menu. The user then clicks on the 'Close' button to close the GUI. At this time, the value selected by the user is passed out into 'a'.
In this example, the GUI function contains the following:
if nargin == 1 % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
% Set the value of the popup based on the input value
set(handles.popupmenu1,'Value',varargin{1})
% Set userdata property of the pushbutton so that the code 'waits' until this value is changed
set(handles.pushbutton1,'UserData','edit')
% Use WAITFOR to have the GUI 'pause' until the userdata property is changed to 'read'
waitfor(handles.pushbutton1,'UserData','read')
if nargout > 0
% pass the value of the popup to varargout
varargout{1} = get(handles.popupmenu1, 'Value');
% close window
delete(fig);
end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
catch
disp(lasterr);
end
end
The callback for the popupmenu is not used. However, the callback for the pushbutton sets the 'UserData' property value to 'read'.
set(h,'UserData','read')
Once this occurs, the WAITFOR function resumes execution of the code and the value of the popupmenu is retrieved. The value is passed to VARARGOUT and the GUI is closed.
Related Question