MATLAB: Programatically add OpeningFcn in GUI

guiguidehandlesMATLABmatlab gui

I have programatically created a GUI app using a single function file (e.g. mygui.m) and putting all my code in that single file. Now I need to add an OpeningFcn in that code. Where and how should I add that OpeningFcn in my code so that I can add data in handles variable in that OpeningFcn to access it later in my other functions?

Best Answer

  • OpenFcn is not part of MATLAB itself. It is part of GUIDE. The boilerplate code inserted by GUIDE calls a routine that sets up OpenFcn to be called.
    The handles structure itself is also an invention of GUIDE, but guidata() is part of MATLAB itself.
    What is part of MATLAB itself is CreateFcn callbacks for most objects. The order that the object callbacks are invoked is not made clear.
    You can add a CreateFcn callback to your figure. However at the time it is invoked your handles structure is not likely to be fully populated yet, partly because the handles structure is a GUIDE artifact.
    The way that the handles structure is created in GUIDE is that the all of the objects are created first (by loading the stored figure) and after that, after all of the CreateFcn have been run, GUIDE finds all of the tagged handles that are children of the figure and creates a struct from them and only then guidata() it into place as the handles structure.
    The good news is that since you are creating your figure elements by code, instead of adding a OpenFcn callback, you just put whatever code you want after you create the objects. Possibly including creating a handles structure if you happen to like that programming model.
    Note that the presence of the handles structure as an argument to gui callbacks is yet another GUIDE artifact. MATLAB does not pass handles around by itself: GUIDE manipulates the various Callback and related *Fcn properties to add code that passes in the handles structure.