Access gui handles in a callback function triggered by an object outside of the gui in Matlab

397 views Asked by At

I built this GUI in Matlab to interact with data. I have created a data environment object to facilitate interaction with data. This object triggers events and I want the GUI to listen to some of these events. So, as you can see in the code below I use the instruction addlistener to link the event to a local function. The issue is that this local function has no access to the GUI handles, do you have any thought on how tho solve this issue? Thanks

function varargout = myGUI(varargin)
...
end

function varargout = myGUI_OutputFcn(hObject, eventdata, handles) 
    varargout{1} = handles.output;
    dataEnv = getappdata(hObject.Parent, 'ratData');
    addlistener(dataEnv,'TrialChanged',@respond_TrialChanged);
end

function respond_TrialChanged(dataEnv, eventData)
    do_something(handles) % I want to access the GUI handles here
end

function do_something(handles)
    ...
end
1

There are 1 answers

1
Marcin On BEST ANSWER

You can use anonymus functions as callbacks which will provide the handles. For example:

function varargout = myGUI_OutputFcn(hObject, eventdata, handles) 
    varargout{1} = handles.output;
    dataEnv = getappdata(hObject.Parent, 'ratData');
    addlistener(dataEnv,'TrialChanged',@(e,d) respond_TrialChanged(e,d,handles.output));
end

function respond_TrialChanged(dataEnv, eventData, handles) 
    do_something(handles) % I want to access the GUI handles here
end

The tird argument to the anonymous functions is handle or handles, or whatever you want to pass within the scope of myGUI_OutputFcn into respond_TrialChanged.

Hope this helps.