How to create a variable number of checkboxes in GUI?
16 views (last 30 days)
Show older comments
I'm trying to create a GUI with checkboxes, with the number of checkboxes being dependable on an input variable (here "stages"). In this case, "stages = 5", but "stages" will probably vary between 1-10 or so. I used a for-loop to create the desired number of checkboxes which are stored in a vector, but the problem is to assign each checkbox a specific function with "callback". With this code, checking different boxes results in the same action, that is: "A(5,1)=1". My wish is obviously to get "A(x,1)=1", where x = box number (or to have a complete different solution).
stages = 5;
fig = figure('Visible','off');
box = zeros(stages,1);
panel = uipanel('parent',fig,...
'Title','Choose stages to plot',...
'position',[.01 .05 .25 .95]);
A=zeros(stages,1);
for i = 1:stages
box(i,1) = uicontrol('parent',panel,'style','checkbox',...
'string',i,...
'position',[20 360-i*25 40 20],...
'callback','A(i,1)=1');
end
set(fig,'Visible','on')
Cheers
0 Comments
Answers (1)
Sean de Wolski
on 1 Jul 2014
Callback should be
,'callback',@(src,evt)mycb(src,evt,i));
Now on each iteration of the for-loop a static snapshot of i is taken and the function mycb will receive it.
function mycb(src,evt,i)
A(i,1) = 1
% Do whatever with A
end
But now you have to worry about what happens to A after the function exits. What do you want to do with A?
2 Comments
Sean de Wolski
on 1 Jul 2014
In that case I would not have the checkboxes do anything. When the later functions go to figure out what to plot, have them query the checkbox's 'Value' and make decisions then.
See Also
Categories
Find more on Graphics Object Programming 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!