matlabcallbackmatlab-guidehandles

How to access non GUIDE handles in GUIDE callbacks


So I have a large legacy GUIDE GUI, that I didn't create but am tasked to expand on. Now I always write my GUI's by hand without GUIDE and have been busy cleaning this one up and fixing it, short of rewriting the whole thing without GUIDE.

So amongst other things I've manually added new GUI objects to the GUI within the _OpeningFcn. So far so good, they do what they should I can add callbacks and functionality as I would expect.

The problem I have though is that if I want to add something referencing the new elements within GUIDE callbacks (ie preexisting callbacks) the handle struct (that is passed to the GUIDE callback as usual) doesn't contain any of the objects I've added within the _OpeningFcn. Thusly I cannot manipulate the new objects from old callbacks.

I presume this has something to do with the fact that I haven't actually saved/assigned the expanded handles object at the end of the _OpeningFcn. But I am not sure if that is supposed to be the way to do it or how to do it.

I hope I've described the problem I have in a concise and precise fashion. Thanks for any help.


Solution

  • If I understand correctly, you are adding GUI elements in the opening function, then adding the handle to those objects to the handles structure, in _OpeningFcn.

    If this is the case, any changes you make to handles itself will be treated as purely local. To apply these changes and make them available throughout the whole scope of your GUI, simply execute the following command at the end of your _OpeningFcn method:

    function YourGui_OpeningFcn(hObject, eventdata, handles, varargin)
        ...
        handles . button = uicontrol ( 'Style' , 'pushbutton' , ...
                                       'String' , 'My Fancy Button', ...
                                       'Position' , [315,220,70,25] );
        ...
    
        guidata ( hObject , handles )
    end
    

    If you neglect the use of guidata at the end of the function, the changes will not stick.