Question

I am creating GUI in matlab using GUIDE. I want to create new field in handles when mouse left button is down, modify the field when mouse is moving and delete it when button is released. But Windowbuttonmotionfcn callback doesn't see that new field. So, here is code example:

function fig_OpeningFcn(hObject, eventdata, handles, varargin)

   handles.output = hObject;
   guidata(hObject, handles);

   set(hObject,'windowbuttonmotionfcn',{@fh_wbmfcn,handles});
   set(hObject, 'windowbuttondownfcn',{@fh_wbdfcn, handles});
   set(hObject, 'windowbuttonupfcn',{@fh_wbufcn, handles});

function fh_wbmfcn(hObject, eventdata, handles)
   isfield(handles, 'new_field') % it is always 0, but should be 1 when button is down

function fh_wbdfcn(hObject, eventdata, handles)
   handles.new_field=1;
   guidata(hObject, handles);

function fh_wbufcn(hObject, eventdata, handles)
   if isfield(handles, 'new_field')
   handles=rmfield(handles,'new_field');
   guidata(hObject, handles);
   end
Was it helpful?

Solution

When you specify a callback like this:

set(hObject,'windowbuttonmotionfcn',{@fh_wbmfcn,handles});

The value of handles will always be the one you set at that point, since you're only passing the value of the handles variable.

Alternatively, the following should work:

set(hObject,'windowbuttonmotionfcn', @(obj,evt) fh_wbmfc(obj,evt, guidata(gcbo));

This will evaluate guidata(gcbo) always at execution time of the callback - and hence give you the current handles value.

Alternative no. 2 (my personal preference):

% remove handles from callback definition
set(hObject,'windowbuttonmotionfcn', @fh_wbmfc);

% and get current handle value in the callback function:
def fh_wbmfc(object, evt)
    handles = guidata(object);
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top