Structure of handles of GUIs MATLAB

橙三吉。 提交于 2020-01-05 03:46:28

问题


I have three GUIs in MATLAB. The tag of each of them is 'P0', 'P1' and 'P2'. I would like to put the handles of all three GUIs in a structure and be able to get to this structure from any of three GUIs and update the values in it. What is the best way to accomplish this?


回答1:


You have a couple of options on how to do this. One way would be to use the root graphics object along with setappdata and getappdata to store and retrieve values.

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);

Then from within your callback, you'd simply fetch this struct and use it directly

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

Another option is to use a handle class to store your values and then you can store a reference to this handle class within the handles struct of each GUI. When you make changes to this struct, the changes will be reflected in all GUIs.

An easy way to do this would be to use structobj (Disclaimer: I am the developer) which will convert any struct into a handle object.

% 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)

Since we stored a thing within the guidata of the figure, it will automatically be passed to your callback via the standard handles input argument. So now your callback would look something like:

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

The benefit of this approach is that you can have multiple instances of your three GUIs running at the same time and the data will not interfere with each other.



来源:https://stackoverflow.com/questions/41466664/structure-of-handles-of-guis-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!