MATLAB: Guidata doesn’t save modified handles structure in OpeningFcn of GUI

guidata

Hi everyone,
I'm implementing a GUI-based simulation program comprising one Main GUI and several "Sub" GUIs. The Sub GUIs are opened from within the callbacks of the Main GUI in the following manner:
% open SingleModesFig in MainFig
singleModesFig = SingleModesFig;
handlesSingleModesFig = guihandles(singleModesFig);
guidata(singleModesFig,handlesSingleModesFig);
In this example, SingleModesFig is the name of a Sub GUI. In the OpeningFcn of SingleModesFig I modify the handles structure by appending some fields and try to save it back using guidata():
% opening function of SingleModesFig
function SingleModesFig_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
handles.treshold = 50;
handles.N = 1; % and so on ...
% save back handles struct
guidata(hObject,handles);
However, when entering any callback in the Sub GUI all the added fields (output, threshold, N,…) have disappeared:
% example callback in SingleModesFig
function ExampleButton_Callback(hObject, eventdata, handles)
% do something with handles struct
a = handles.treshold; % PRODUCES ERROR: no such field 'treshold' in handles
Interestingly, when I open the SingleModesFig not from code but manually by pressing "Run", guidata() works fine and the handles structure is saved back correctly. I tried to figure out the reason for this, but haven't found any sensible explanation. Does it create confusion for guidata if multiple figures are opened simultaneously? I tried to replace 'hObject' by an explicit search for the figure using its tag, but this doesn't solved the problem as well. In addition, I would rather like to understand this behavior and fix it than to incorporate workarounds using the base workspace.
I appreciate your hints and help.

Best Answer

Remove the following lines from the MainFig pushbutton callback:
handlesSingleModesFig = guihandles(singleModesFig);
guidata(singleModesFig,handlesSingleModesFig);
You are overwriting the changes made in the OpeningFcn of the SingleModesFig by creating a new handles structure. There is no need to create a handles structure for SingleModesFig from the MainFig, GUIDE will create the handles structure automatically when opening up the new GUI