Write Callbacks in GUIDE
Note
The GUIDE environment will be removed in a future release. After GUIDE is removed, existing GUIDE apps will continue to run in MATLAB® but they will not be editable in GUIDE.
To continue editing an existing GUIDE app, see GUIDE Migration Strategies for information on how to help maintain compatibility of the app with future MATLAB releases. To create new apps interactively, Develop Apps Using App Designer instead.
Callbacks for Different User Actions
UI and graphics components have certain properties that you
can associate with specific callback functions. Each of these properties
corresponds to a specific user action. For example, a uicontrol has
a property called Callback
. You can set the value
of this property to be a handle to a callback function, an anonymous
function, or a character vector containing a MATLAB expression.
Setting this property makes your app respond when the user interacts
with the uicontrol. If the Callback
property
has no specified value, then nothing happens when the user interacts
with the uicontrol.
This table lists the callback properties that are available, the user actions that trigger the callback function, and the most common UI and graphics components that use them.
Callback Property | User Action | Components That Use This Property |
---|---|---|
ButtonDownFcn | End user presses a mouse button while the pointer is on the component or figure. | |
Callback | End user triggers the component. For example: selecting a menu item, moving a slider, or pressing a push button. | |
CellEditCallback | End user edits a value in a table whose cells are editable. | |
CellSelectionCallback | End user selects cells in a table. | |
ClickedCallback | End user clicks the push tool or toggle tool with the left mouse button. | |
CloseRequestFcn | The figure closes. | |
CreateFcn | Callback executes when MATLAB creates the object, but before it is displayed. |
|
DeleteFcn | Callback executes just before MATLAB deletes the figure. |
|
KeyPressFcn | End user presses a keyboard key while the pointer is on the object. | |
| End user releases a keyboard key while the pointer is on the object. | |
OffCallback | Executes when the | |
OnCallback | Executes when the | |
| End user resizes a button group, figure, or panel whose | |
SelectionChangedFcn | End user selects a different radio button or toggle button within a button group. | |
WindowButtonDownFcn | End user presses a mouse button while the pointer is in the figure window. | |
WindowButtonMotionFcn | End user moves the pointer within the figure window. | |
WindowButtonUpFcn | End user releases a mouse button. | |
WindowKeyPressFcn | End user presses a key while the pointer is on the figure or any of its child objects. | |
WindowKeyReleaseFcn | End user releases a key while the pointer is on the figure or any of its child objects. | |
| End user turns the mouse wheel while the pointer is on the figure. |
GUIDE-Generated Callback Functions and Property Values
How GUIDE Manages Callback Functions and Properties
After you add a uicontrol
, uimenu
, or uicontextmenu
component to
your UI, but before you save it, GUIDE populates the
Callback
property with the value,
%automatic
. This value indicates that GUIDE will generate
a name for the callback function.
When you save your UI, GUIDE adds an empty callback function definition to
your code file, and it sets the control’s Callback
property
to be an anonymous function. This function definition is an example of a
GUIDE-generated callback function for a push
button.
function pushbutton1_Callback(hObject,eventdata,handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) end
myui
, then GUIDE sets the
push button’s Callback
property to the following
value:@(hObject,eventdata)myui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
pushbutton1_Callback
. This anonymous function has four
input arguments. The first argument is the name of the callback function. The
last three arguments are provided by MATLAB, and are discussed in the section, GUIDE Callback Syntax.Note
GUIDE does not automatically generate callback functions for other UI components, such as tables, panels, or button groups. If you want any of these components to execute a callback function, then you must create the callback by right-clicking on the component in the layout, and selecting an item under View Callbacks in the context menu.
GUIDE Callback Syntax
All callbacks must accept at least three input arguments:
hObject
— The UI component that triggered the callback.eventdata
— A variable that contains detailed information about specific mouse or keyboard actions.handles
— Astruct
that contains all the objects in the UI. GUIDE uses theguidata
function to store and maintain this structure.
For the callback function to accept additional arguments, you must put the additional arguments at the end of the argument list in the function definition.
The eventdata Argument
The eventdata
argument provides detailed information to
certain callback functions. For example, if the end user triggers the
KeyPressFcn
, then MATLAB provides information regarding the specific key (or combination of
keys) that the end user pressed. If eventdata
is not
available to the callback function, then MATLAB passes it as an empty array. The following table lists the
callbacks and components that use eventdata
.
Callback Property Name | Component |
---|---|
WindowKeyPressFcn WindowKeyReleaseFcn WindowScrollWheel | figure |
KeyPressFcn | figure , uicontrol , uitable |
KeyReleaseFcn | figure , uicontrol , uitable |
SelectionChangedFcn | uibuttongroup |
CellEditCallback CellSelectionCallback | uitable |
Share Data Among GUIDE Callbacks
To create controls, menus, and graphics objects in your app that are interdependent, you must explicitly share data with the parts of your app that need to access the component.
Method | Description | Requirements and Trade-Offs |
---|---|---|
Share UserData | Get or set property values directly through the component object. All UI components have a
|
|
Share Application Data | Associate data with a specific component using the
|
|
Use guidata | Share data with the figure window using the |
|
Share UserData in GUIDE Apps
UI components contain useful information in their properties. For example, you
can find the current position of a slider by querying its
Value
property. In addition, all components have a
UserData
property, which can store any MATLAB variable. All callback functions can access the value stored in
the UserData
property as long as those functions can access
the component.
To set up a GUIDE app for sharing slider data with the
UserData
property, perform these steps:
In the Command Window, type
guide
to open a new blank GUI.Display the names of the UI components in the component palette:
Select File > Preferences > GUIDE.
Select Show names in component palette.
Click OK.
Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.
Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.
Select File > Save. Save the UI as
myslider.fig
. MATLAB opens the code file in the Editor.Set the initial value of the
UserData
property in the opening function,myslider_OpeningFcn
. This function executes just before the UI is visible to users.In
myslider_OpeningFcn
, insert these commands immediately after the command,handles.output = hObject
.After you add the commands,data = struct('val',0,'diffMax',1); set(handles.slider1,'UserData',data);
myslider_OpeningFcn
looks like this.Notice thatfunction myslider_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to junk (see VARARGIN) % Choose default command line output for myslider handles.output = hObject; data = struct('val',0,'diffMax',1); set(handles.slider1,'UserData',data); % Update handles structure guidata(hObject, handles); % UIWAIT makes myslider wait for user response % uiwait(handles.figure1);
handles
is an input argument tomyslider_OpeningFcn
. Thehandles
variable is a structure that contains all the components in the UI. Each field in this structure corresponds to a separate component. Each field name matches theTag
property of the corresponding component. Thus,handles.slider1
is the slider component in this UI. The command,set(handles.slider1,'UserData',data)
stores the variable,data
, in theUserData
property of the slider.Add code to the slider callback for modifying the data. Add these commands to the end of the function,
slider1_Callback
.After you add the commands,maxval = get(hObject,'Max'); sval = get(hObject,'Value'); diffMax = maxval - sval; data = get(hObject,'UserData'); data.val = sval; data.diffMax = diffMax; % Store data in UserData of slider set(hObject,'UserData',data);
slider1_Callback
looks like this.Notice that% --- Executes on slider movement. function slider1_Callback(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider maxval = get(hObject,'Max'); sval = get(hObject,'Value'); diffMax = maxval - sval; data = get(hObject,'UserData'); data.val = sval; data.diffMax = diffMax; % Store data in UserData of slider set(hObject,'UserData',data);
hObject
is an input argument to theslider1_Callback
function.hObject
is always the component that triggers the callback (the slider, in this case). Thus,set(hObject,'UserData',data)
, stores thedata
variable in theUserData
property of the slider.Add code to the push button callback for retrieving the data. Add these commands to the end of the function,
pushbutton1_Callback
.After you add the commands,% Get UserData from the slider data = get(handles.slider1,'UserData'); currentval = data.val; diffval = data.diffMax; display([currentval diffval]);
pushbutton1_Callback
looks like this.% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get UserData from the slider data = get(handles.slider1,'UserData'); currentval = data.val; diffval = data.diffMax; display([currentval diffval]);
This code uses the handles structure to access the slider. The command,
data = get(handles.slider1,'UserData')
, gets the slider’sUserData
property. Then, thedisplay
function displays the stored values.Save your code by pressing Save in the Editor Toolstrip.
Share Application Data in GUIDE Apps
To store application data, call the setappdata
function:
setappdata(obj,name,value);
obj
, is the component object in which to store the
data. The second input, name
, is a friendly name that
describes the value. The third input, value
, is the value you
want to store.To retrieve application data, use the getappdata
function:
data = getappdata(obj,name);
obj
, must be the component object containing the data.
The second input, name
, must match the name you used to store
the data. Unlike the UserData
property, which only holds
only one variable, you can use setappdata
to store multiple
variables.To set up a GUIDE app for sharing application data, perform these steps:
In the Command Window, type
guide
to open a new blank GUI.Display the names of the UI components in the component palette:
Select File > Preferences > GUIDE.
Select Show names in component palette.
Click OK.
Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.
Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.
Select File > Save. Save the UI as
myslider.fig
. MATLAB opens the code file in the Editor.Set the initial value of the application data in the opening function,
myslider_OpeningFcn
. This function executes just before the UI is visible to users. Inmyslider_OpeningFcn
, insert these commands immediately after the command,handles.output = hObject
.After you add the commands,setappdata(handles.figure1,'slidervalue',0); setappdata(handles.figure1,'difference',1);
myslider_OpeningFcn
looks like this.Notice thatfunction myslider_OpeningFcn(hObject,eventdata,handles,varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to junk (see VARARGIN) % Choose default command line output for junk handles.output = hObject; setappdata(handles.figure1,'slidervalue',0); setappdata(handles.figure1,'difference',1); % Update handles structure guidata(hObject, handles); % UIWAIT makes junk wait for user response (see UIRESUME) % uiwait(handles.figure1);
handles
is an input argument tomyslider_OpeningFcn
. Thehandles
variable is a structure that contains all the components in the UI. Each field in this structure corresponds to a separate component. Each field name matches theTag
property of the corresponding component. In this case,handles.figure1
is the figure object. Thus,setappdata
can use this figure object to store the data.Add code to the slider callback for changing the data. Add these commands to the end of the function,
slider1_Callback
.After you add the commands,maxval = get(hObject,'Max'); currval = get(hObject,'Value'); diffMax = maxval - currval; % Store application data setappdata(handles.figure1,'slidervalue',currval); setappdata(handles.figure1,'difference',diffMax);
slider1_Callback
looks like this.This callback function has access to thefunction slider1_Callback(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider maxval = get(hObject,'Max'); currval = get(hObject,'Value'); diffMax = maxval - currval; % Store application data setappdata(handles.figure1,'slidervalue',currval); setappdata(handles.figure1,'difference',diffMax);
handles
structure, so thesetappdata
commands store the data inhandles.figure1
.Add code to the push button callback for retrieving the data. Add these commands to the end of the function,
pushbutton1_Callback
.After you add the commands,% Retrieve application data currentval = getappdata(handles.figure1,'slidervalue'); diffval = getappdata(handles.figure1,'difference'); display([currentval diffval]);
pushbutton1_Callback
looks like this.This callback function has access to the% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Retrieve application data currentval = getappdata(handles.figure1,'slidervalue'); diffval = getappdata(handles.figure1,'difference'); display([currentval diffval]);
handles
structure, so thegetappdata
commands retrieve the data fromhandles.figure1
.Save your code by pressing Save in the Editor Toolstrip.
Use guidata
to Store and Share Data in GUIDE Apps
GUIDE uses the guidata
function to store a
structure called handles
, which contains all the UI
components. MATLAB passes the handles
array to every callback
function. If you want to use guidata
to share additional
data, then add fields to the handles
structure in the opening
function. The opening function is a function defined near the top of your code
file that has _OpeningFcn
in the name.
To modify your data in a callback function, modify the
handles
structure, and then store it using the
guidata
function. This slider callback function shows
how to modify and store the handles
structure in a GUIDE
callback
function.
function slider1_Callback(hObject, eventdata,handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range handles.myvalue = 2; guidata(hObject,handles); end
GUIDE Example: Share Slider Data Using guidata
Here is a prebuilt GUIDE app that uses the guidata
function to share data between a slider and a text field. When you move the slider, the number displayed in the text field changes to show the new slider position.
GUIDE Example: Share Data Between Two Apps
Here is a prebuilt GUIDE app that uses application data and the guidata
function to share data between two dialog boxes. When you enter text in the second dialog box and click OK, the button label changes in the first dialog box.
In changeme_main.m
, the buttonChangeMe_Callback
function executes this command to display the second dialog box:
changeme_dialog('changeme_main', handles.figure)
The handles.figure
input argument is the Figure
object for the changeme_main dialog box.
The changeme_dialog
function retrieves the handles
structure from the Figure
object. Thus, the entire set of components in the changeme_main dialog box is available to the second dialog box.
GUIDE Example: Share Data Among Three Apps
Here is a prebuilt GUIDE app that uses guidata
and UserData
to share data among three app windows. The large window is an icon editor that accepts information from the tool palette and color palette windows.
In guide_inconeditor.m
, the function guide_iconeditor_OpeningFcn
contains this command:
colorPalette = guide_colorpalette('iconEditor', hObject)
The arguments are:
'iconEditor'
specifies that a callback in the guide_iconEditor window triggered the execution of the function.hObject
is theFigure
object for the guide_iconEditor window.colorPalette
is theFigure
object for the guide_colorPalette window.
Similarly, guide_iconeditor_OpeningFcn
calls the guide_toolpalette
function with similar input and output arguments.
Passing the Figure
object between these functions allows the guide_iconEditor window to access the handles
structure of the other two windows. Likewise, the other two windows can access the handles
structure for the guide_iconEditor window.
Renaming and Removing GUIDE-Generated Callbacks
Renaming Callbacks
GUIDE creates the name of a callback function by combining the component’s
Tag
property and the callback property name. If you
change the component’s Tag
value, then GUIDE changes the
callback's name the next time you save the UI.
If you decide to change the Tag
value after saving the
UI, then GUIDE updates the following items (assuming that all components have
unique Tag
values).
Component's callback function definition
Component’s callback property value
References in the code file to the corresponding field in the
handles
structure
To rename a callback function without changing the component’s
Tag
property:
Change the name in the callback function definition.
Update the component’s callback property by changing the first argument passed to the anonymous function. For example, the original callback property for a push button might look like this:
@(hObject,eventdata)myui('pushbutton1_Callback',... hObject,eventdata,guidata(hObject))
In this example, you must change,
'pushbutton1_Callback'
to the new function name.Change all other references to the old function name to the new function name in the code file.
Deleting Callbacks
You can delete a callback function when you want to remove or change the function that executes when the end user performs a specific action. To delete a callback function:
Search and replace all instances that refer to the callback function in your code.
Open the UI in GUIDE and replace all instances that refer to the callback function in the Property Inspector.
Delete the callback function.