Main Content

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.

axes, figure, uibuttongroup, uicontrol, uipanel, uitable,

Callback

End user triggers the component. For example: selecting a menu item, moving a slider, or pressing a push button.

uicontextmenu, uicontrol, uimenu

CellEditCallback

End user edits a value in a table whose cells are editable.

uitable

CellSelectionCallback

End user selects cells in a table.

uitable

ClickedCallback

End user clicks the push tool or toggle tool with the left mouse button.

uitoggletool, uipushtool

CloseRequestFcn

The figure closes.

figure

CreateFcn

Callback executes when MATLAB creates the object, but before it is displayed.

axes, figure, uibuttongroup, uicontextmenu, uicontrol, uimenu, uipushtool, uipanel, uitable, uitoggletool, uitoolbar

DeleteFcn

Callback executes just before MATLAB deletes the figure.

axes, figure, uibuttongroup, uicontextmenu, uicontrol, uimenu, uipushtool, uipanel, uitable, uitoggletool, uitoolbar

KeyPressFcn

End user presses a keyboard key while the pointer is on the object.

figure, uicontrol, uipanel, uipushtool, uitable, uitoolbar

KeyReleaseFcn

End user releases a keyboard key while the pointer is on the object.

figure, uicontrol, uitable

OffCallback

Executes when the State of a toggle tool changes to 'off'.

uitoggletool

OnCallback

Executes when the State of a toggle tool changes to 'on'.

uitoggletool

SizeChangedFcn

End user resizes a button group, figure, or panel whose Resize property is 'on'.

figure, uipanel, uibuttongroup

SelectionChangedFcn

End user selects a different radio button or toggle button within a button group.

uibuttongroup

WindowButtonDownFcn

End user presses a mouse button while the pointer is in the figure window.

figure

WindowButtonMotionFcn

End user moves the pointer within the figure window.

figure

WindowButtonUpFcn

End user releases a mouse button.

figure

WindowKeyPressFcn

End user presses a key while the pointer is on the figure or any of its child objects.

figure

WindowKeyReleaseFcn

End user releases a key while the pointer is on the figure or any of its child objects.

figure

WindowScrollWheelFcn

End user turns the mouse wheel while the pointer is on the figure.

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
If you save this UI with the name, myui, then GUIDE sets the push button’s Callback property to the following value:
@(hObject,eventdata)myui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
This is an anonymous function that serves as a reference to the function, 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 — A struct that contains all the objects in the UI. GUIDE uses the guidata 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 NameComponent
WindowKeyPressFcn
WindowKeyReleaseFcn
WindowScrollWheel
figure
KeyPressFcnfigure, uicontrol, uitable
KeyReleaseFcnfigure, uicontrol, uitable
SelectionChangedFcnuibuttongroup
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.

MethodDescriptionRequirements and Trade-Offs
Share UserData

Get or set property values directly through the component object.

All UI components have a UserData property that can store any MATLAB data.

  • Requires access to the component to set or retrieve the properties.

  • UserData holds only one variable at a time, but you can store multiple values as a struct array or cell array.

Share Application Data

Associate data with a specific component using the setappdata function. You can access it later using the getappdata function.

  • Requires access to the component to set or retrieve the application data.

  • Can share multiple variables.

Use guidata

Share data with the figure window using the guidata function.

  • Stores or retrieves the data through any UI component.

  • Stores only one variable at a time, but you can store multiple values as a struct array or cell array.

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:

  1. In the Command Window, type guide to open a new blank GUI.

  2. Display the names of the UI components in the component palette:

    1. Select File > Preferences > GUIDE.

    2. Select Show names in component palette.

    3. Click OK.

  3. Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  4. Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  5. Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in the Editor.

  6. 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.

    data = struct('val',0,'diffMax',1);
    set(handles.slider1,'UserData',data);
    
    After you add the commands, myslider_OpeningFcn looks like this.
    function 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);
    
    Notice that handles is an input argument to myslider_OpeningFcn. The handles 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 the Tag 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 the UserData property of the slider.

  7. Add code to the slider callback for modifying the data. Add these commands to the end of the function, slider1_Callback.

    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);
    After you add the commands, slider1_Callback looks like this.
    % --- 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);
    
    Notice that hObject is an input argument to the slider1_Callback function. hObject is always the component that triggers the callback (the slider, in this case). Thus, set(hObject,'UserData',data), stores the data variable in the UserData property of the slider.

  8. Add code to the push button callback for retrieving the data. Add these commands to the end of the function, pushbutton1_Callback.

    % Get UserData from the slider
    data = get(handles.slider1,'UserData');
    currentval = data.val;
    diffval = data.diffMax;
    display([currentval diffval]);
    After you add the commands, 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’s UserData property. Then, the display function displays the stored values.

  9. 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);
The first input, 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);
The component, 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:

  1. In the Command Window, type guide to open a new blank GUI.

  2. Display the names of the UI components in the component palette:

    1. Select File > Preferences > GUIDE.

    2. Select Show names in component palette.

    3. Click OK.

  3. Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  4. Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  5. Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in the Editor.

  6. 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. In myslider_OpeningFcn, insert these commands immediately after the command, handles.output = hObject.

    setappdata(handles.figure1,'slidervalue',0); 
    setappdata(handles.figure1,'difference',1);
    After you add the commands, myslider_OpeningFcn looks like this.
    function 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);
    
    Notice that handles is an input argument to myslider_OpeningFcn. The handles 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 the Tag 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.

  7. Add code to the slider callback for changing the data. Add these commands to the end of the function, slider1_Callback.

    maxval = get(hObject,'Max');  
    currval = get(hObject,'Value');  
    diffMax = maxval - currval;   
    % Store application data
    setappdata(handles.figure1,'slidervalue',currval); 
    setappdata(handles.figure1,'difference',diffMax);
    After you add the commands, slider1_Callback looks like this.
    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');  
    currval = get(hObject,'Value');  
    diffMax = maxval - currval;   
    % Store application data
    setappdata(handles.figure1,'slidervalue',currval); 
    setappdata(handles.figure1,'difference',diffMax);
    This callback function has access to the handles structure, so the setappdata commands store the data in handles.figure1.

  8. Add code to the push button callback for retrieving the data. Add these commands to the end of the function, pushbutton1_Callback.

    % Retrieve application data
    currentval = getappdata(handles.figure1,'slidervalue');
    diffval = getappdata(handles.figure1,'difference');
    display([currentval diffval]);
    After you add the commands, 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)
    
    % Retrieve application data
    currentval = getappdata(handles.figure1,'slidervalue');
    diffval = getappdata(handles.figure1,'difference');
    display([currentval diffval]);
    This callback function has access to the handles structure, so the getappdata commands retrieve the data from handles.figure1.

  9. 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 the Figure object for the guide_iconEditor window.

  • colorPalette is the Figure 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:

  1. Change the name in the callback function definition.

  2. 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.

  3. 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:

  1. Search and replace all instances that refer to the callback function in your code.

  2. Open the UI in GUIDE and replace all instances that refer to the callback function in the Property Inspector.

  3. Delete the callback function.

Related Topics