FAQ: Incomplete handles struct in callbacks

1 view (last 30 days)
Jan
Jan 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?

Answers (1)

Jan
Jan 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
Jan on 28 Dec 2012
@Editors: Please improve this answer by editing it. Thanks.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!