在 Matlab gui 中使用“ButtonDownFcn”时将句柄传递给子函数
Passing handles to subfunction when using `ButtonDownFcn` in Matlab gui
我需要使用 Matlab Gui 根据用户点击的位置处理图像。我找到了建议使用 ButtonDownFcn
的例子:
function buttonSelectSuperpixels_Callback(hObject, eventdata, handles)
h = handles.myCanvas;
set(h,'ButtonDownFcn',@position_and_button);
然后像这样处理子函数position_and_button
中的点击点:
function position_and_button(hObject,eventdata)
Position = get( ancestor(hObject,'axes'), 'CurrentPoint' );
Button = get( ancestor(hObject,'figure'), 'SelectionType' );
但是我需要在最后一个子函数中处理一些其他变量。是否可以将 handles
变量传递给 position_and_button
并更新它?
我试图将 handles
作为参数传递,但它似乎不起作用。
您可以将 handles
结构传递给您的回调,方法是使用匿名函数将其添加为输入
set(h, 'ButtonDownFcn', @(src, evnt)position_and_button(src, evnt, handles))
或者元胞数组
set(h, 'ButtonDownFcn', {@position_and_button, handles})
不过,问题是 MATLAB 传递变量 按值 而不是按引用。因此,当您定义这些回调时,它们将创建 handles
的 copy,就像创建回调时的样子一样。正是这个 copy 将被传递给另一个函数。此外,您在回调中对 handles
所做的任何更改都会对 另一个副本 进行,并且其他函数将永远不会看到这些更改。
为避免这种行为,您可以在回调中从 guidata
中检索 handles
结构(确保您拥有最新版本)。然后,如果您对其进行任何更改,则需要在这些更改后保存 guidata
,所有其他功能将能够看到这些更改。
function position_and_button(src, evnt)
% Get the handles struct
handles = guidata(src);
% Now use handles struct however you want including changing variables
handles.variable2 = 2;
% Now save the changes
guidata(src, handles)
% Update the CData of the image rather than creating a new one
set(src, 'CData', newimage)
end
在这种情况下,您只需指定回调函数的默认两个输入。
我需要使用 Matlab Gui 根据用户点击的位置处理图像。我找到了建议使用 ButtonDownFcn
的例子:
function buttonSelectSuperpixels_Callback(hObject, eventdata, handles)
h = handles.myCanvas;
set(h,'ButtonDownFcn',@position_and_button);
然后像这样处理子函数position_and_button
中的点击点:
function position_and_button(hObject,eventdata)
Position = get( ancestor(hObject,'axes'), 'CurrentPoint' );
Button = get( ancestor(hObject,'figure'), 'SelectionType' );
但是我需要在最后一个子函数中处理一些其他变量。是否可以将 handles
变量传递给 position_and_button
并更新它?
我试图将 handles
作为参数传递,但它似乎不起作用。
您可以将 handles
结构传递给您的回调,方法是使用匿名函数将其添加为输入
set(h, 'ButtonDownFcn', @(src, evnt)position_and_button(src, evnt, handles))
或者元胞数组
set(h, 'ButtonDownFcn', {@position_and_button, handles})
不过,问题是 MATLAB 传递变量 按值 而不是按引用。因此,当您定义这些回调时,它们将创建 handles
的 copy,就像创建回调时的样子一样。正是这个 copy 将被传递给另一个函数。此外,您在回调中对 handles
所做的任何更改都会对 另一个副本 进行,并且其他函数将永远不会看到这些更改。
为避免这种行为,您可以在回调中从 guidata
中检索 handles
结构(确保您拥有最新版本)。然后,如果您对其进行任何更改,则需要在这些更改后保存 guidata
,所有其他功能将能够看到这些更改。
function position_and_button(src, evnt)
% Get the handles struct
handles = guidata(src);
% Now use handles struct however you want including changing variables
handles.variable2 = 2;
% Now save the changes
guidata(src, handles)
% Update the CData of the image rather than creating a new one
set(src, 'CData', newimage)
end
在这种情况下,您只需指定回调函数的默认两个输入。