[英]MATLAB GUI: how to update handles when new objects are created in a subfunction?
[英]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
結構添加為回調來將handles
結構傳遞給回調
set(h, 'ButtonDownFcn', @(src, evnt)position_and_button(src, evnt, handles))
或者是一個單元陣列
set(h, 'ButtonDownFcn', {@position_and_button, handles})
但問題是,MATLAB 按值而不是通過引用傳遞變量。 因此,當您定義這些回調時,它們將在創建回調時查看handles
的副本 。 這個副本將被傳遞給另一個函數。 此外,您對回調中的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
在這種情況下,您只需要指定回調函數的默認兩個輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.