button callback in GUI _OpeningFcn does not update a guidata variable
Show older comments
Consider the following easy example:
function GUI_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 GUI (see VARARGIN)
% Choose default command line output for GUI
handles.output = hObject;
clc
handles.ColVec = []
pushbutton4_Callback(hObject, eventdata, handles)% calling Button4 here
% Update handles structure
guidata(hObject, handles);
and the following callback function for Button4,
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.ColVec = [1 .1 .1];
guidata(hObject,handles)
Naturally when the GUI runs for the very first time, the ColVec should be equal to [1 .1 .1], while it shows empty! handles.ColVec however is equal to [1 .1 .1] when I manually press the Button4! Does somebody know why the handles value cannot be automatically changed when the Button4 is called back in OpeningFcn? and what's the workaround of it to get the ColVec = [1 .1 .1] without manually pressing Button4?
Thanks
1 Comment
Adam
on 27 Mar 2017
Why are you trying to call a callback function in the OpeningFcn? Callback functions should be precisely that, only called when you click the button that they are the callback for. If you want the same behaviour to happen factor out the main code from your callback into a new function that you can call from both places without having to crowbar in spurious arguments like eventdata which have no business being there other than from the pushbutton4 object.
Why can't you do the obvious thing to initialise your vector i.e. put this in the OpeningFcn:
handles.ColVec = [1 0.1 0.1];
?!
Also, as an aside, don't put things like
clc
is a GUI. It does no harm, but it has no place in a GUI, it just adds clutter, and is only a short step away from starting to put things like
clear all
close all
in there too which seems to be favoured by many people writing scripts. These definitely do harm!
Accepted Answer
More Answers (0)
Categories
Find more on Migrate GUIDE Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!