Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

FAQ: Incomplete handles struct in callbacks

Asked by Jan Simon on 28 Dec 2012

Callbacks created by GUIDE get the handles struct as input argument:

   function pushbuttonXY_Callback(hObject, eventdata, handles)

But this handles struct does not contain the expected fields, e.g. handles of other UI-elements. Where do I find the required fields and why are they missing?

0 Comments

Jan Simon

Products

No products are associated with this question.

1 Answer

Answer by Jan Simon on 28 Dec 2012

GUIDE creates the callback during the GUI is created. Then the handles struct stored in the callback ccontains only the fields, which have been created before. Example:

handles.FigureH     = figure;
handles.Pushbutton1 = uicontrol('Style', 'PushButton', ...
                                'String', 'Button 1', ...
                                'Callback', {@pushbutton1_Callback, handles});
guidata(handles.FigureH, handles);  % "handles" stored in the figure
...
function pushbutton1_Callback(hObject, EventData, handles)
disp(isfield(handles, 'Pushbutton1'))
% replies FALSE !!!

This can be solved by avoid using the handles struct from the inputs, but get the latest value using guidata:

function pushbutton1_Callback(hObject, EventData, handles)
handles = guidata(hObject);  % get newest value of handles struct
disp(isfield(handles, 'Pushbutton1'))
% replies TRUE !!!

If the callback adds or modifies a field of the handles struct, do not forget to updated struct afterwards:

function pushbutton1_Callback(hObject, EventData, handles)
handles = guidata(hObject);  % get newest value of handles struct
handles.CurrentTime = datestr(now, 0);
guidata(hObject, handles);   % store updated struct in the figure

The function guidata(H) obtains or stores a struct in the figure, which contains the GUI object with the handle H. H can be the figure's handle also, but using the handle of the calling object is more convenient.

 

The name "handles" does not mean, that this struct could or should contain the handles of GUI objects only. You can store any user defined data also. Alternatively you can call setappdata(FigureH, Data) or set(FigureH, 'UserData', Data) also. The name "handles" and adding the incomplete struct to the callbacks is not an optimal design idea.

1 Comment

Jan Simon on 28 Dec 2012

@Editors: Please improve this answer by editing it. Thanks.

Jan Simon

Contact us