GUI MATLAB的句柄结构

chs*_*ane 1 matlab matlab-figure matlab-guide

我在MATLAB中有三个GUI.每个人的标签是'P0','P1''P2'.我想将所有三个GUI的句柄放在一个结构中,并能够从三个GUI中的任何一个获取此结构并更新其中的值.完成此任务的最佳方法是什么?

Sue*_*ver 5

你有几个选择如何做到这一点.一种方法是使用root图形对象以及setappdatagetappdata存储和检索值.

fig0 = findall(0, 'tag', 'P0');
fig1 = findall(0, 'tag', 'P1');
fig2 = findall(0, 'tag', 'P2');

% Combine the GUIdata into a single struct
handles.P0 = guidata(fig0);
handles.P1 = guidata(fig1);
handles.P2 = guidata(fig2);

% Store this struct in the root object where ALL GUIs can access it
setappdata(0, 'myappdata', handles);
Run Code Online (Sandbox Code Playgroud)

然后从你的回调中,你只需获取这个结构并直接使用它

function mycallback(hObject, evnt, ~)
    % Ignore the handles that is passed in and use your own
    handles = getappdata(0, 'myappdata');

    % Now if you modify it, you MUST save it again
    handles.P0.value = 1;

    setappdata(0, 'myappdata', handles)
end
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用handle来存储您的值,然后您可以在每个GUI 的结构中存储对此句柄类的引用handles.当您对此结构进行更改时,更改将反映在所有GUI中.

一个简单的方法是使用structobj(免责声明:我是开发人员)将任何struct转换为handle对象.

% Create an object that looks like a struct but is a handle class and fill it with the 
% handles struct from each GUI
handles = structobj(guidata(fig0));
update(handles, guidata(fig1));
update(handles, guidata(fig2));

% Now store this in the guidata of each figure
guidata([fig0, fig1, fig2], handles)
Run Code Online (Sandbox Code Playgroud)

由于我们guidata在图中存储了一个东西,它将通过标准handles输入参数自动传递给你的回调.所以现在你的回调看起来像:

function mycallback(hObject, evnt, handles)
    % Access the data you had stored
    old_thing = handles.your_thing;

    % Update the value (changes will propagate across ALL GUIs)
    handles.your_thing = 2;
end
Run Code Online (Sandbox Code Playgroud)

这种方法的好处是,您可以同时运行三个GUI的多个实例,并且数据不会相互干扰.