I'm generating a MATLAB GUI using GUIDE, but I want to create fields when a user clicks on a button. Is there any way to dynamically add new GUI objects in the callbacks?
One way to accomplish this is to create the GUI objects at the start, but set their "Visibility" property to "off". Then, when the user clicks on a button, you set the "Visibility" property back to "on". This way, you won't be making new GUI objects while the GUI is running, you would simply be changing which parts of it are visible or not.
EDIT: If you don't know how many new GUI objects you need until run-time, this is how you would add the new GUI objects to the handles structure (where hFigure is a handle to the GUI figure):
p = uicontrol(hFigure,'Style','pushbutton','String','test',...
'Callback',@p_Callback); % Including callback, if needed
handles.test = p; % Add p to the "test" field of the handles structure
guidata(hFigure,handles); % Add the new handles structure to the figure
You would then of course have to write the callback function for the new GUI object (if it needs one), which might look something like this:
function p_Callback(hObject,eventdata)
handles = guidata(gcbf); % This gets the handles structure from the figure
...
(make whatever computations/changes to GUI are needed)
...
guidata(gcbf,handles); % This is needed if the handles structure is modified
Functions of interest that I used in the above code are: GUIDATA (for storing/retrieving data for a GUI) and GCBF (get handle of parent figure of the object whose callback is currently executing).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With