Create a GUI (which aim to show and change a list of variables) dynamically based on the number of variables

9 views (last 30 days)
Hello people,
I would like to implement a code that generates dynamically a UI.
In this UI, I would like to see and change (with a button) the values of a series of variables.
Let me propose you this example:
Variables.var1.value = 5;
Variables.var2.value = 10;
Variables.var3.value = "text1";
Variables.var4.value = "text2";
Variables.var1.label = "numerical variable 1";
Variables.var2.label = "numerical variable 2";
Variables.var3.label = "alphanumerical variable 3";
Variables.var4.label = "alphanumerical variable 4";
So, I would like to have a code that actually generates automatically the UI showing per each variable (1) the label, (2) the actual value, (3) a button allowing to change the value.
This is the UI I would expect:
Of course, if 10 variables are stored in the Variables structure, the generated UI should display 10 lines, one per each variable.
Many thanks for your help... I am completely lost!
  2 Comments

Sign in to comment.

Accepted Answer

Dennis
Dennis on 31 Aug 2018
As Stephen already pointed out this becomes way easier if you index your structure.
%creating 'Variables'
Variables(1).value=5;
Variables(2).value=10;
Variables(3).value='text1';
Variables(4).value='text2';
for i=4:-1:1
Variables(i).label=['v',num2str(i)];
end
%actual code begins here
for i=size(Variables,2):-1:1
handles.label(i)=uicontrol('style','text','string',Variables(i).label,'position',[40 40+(i-1)*50 100 40]);
if isnumeric(Variables(i).value)
handles.value(i)=uicontrol('style','text','string',num2str(Variables(i).value),'position',[160 40+(i-1)*50 60 40]);
else
handles.value(i)=uicontrol('style','text','string',Variables(i).value,'position',[160 40+(i-1)*50 60 40]);
end
handles.pb(i)=uicontrol('style','pushbutton','string','modify','position',[240 40+(i-1)*50 60 40]);
end
for i=1:size(handles.pb,2)
handles.pb(i).Callback={@modify_cb,handles};
end
%callback for pushbutton
function modify_cb(hObj,~,handles)
label=inputdlg('Label');
value=inputdlg('Value');
for i=1:size(handles.value,2)
if hObj==handles.pb(i)
handles.value(i).String=value;
handles.label(i).String=label;
end
end
end

More Answers (2)

Donato Cereghetti
Donato Cereghetti on 10 Jul 2019
Many thanks for your clear answer! Very helpful.

Abel Szkalisity
Abel Szkalisity on 6 Oct 2020
In case you need this many times you could also check out my dynamic settings GUI tool here: https://se.mathworks.com/matlabcentral/fileexchange/73180-matlab_settings_gui
You should just provide the input structure to it, and it generates all the ui elements for you automatically. It also handles the resize of the container GUI and generates scrollbar if you have too many ui elements.

Categories

Find more on MATLAB Report Generator in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!