Matlab: GUI radio button SelectionChangedFn Callback

Viewed 20

I'm trying to figure out how to make a GUI with radio buttons that will enable/disable options based on radio button selections. Here's an example of one way I have tried:

fig = uifigure('NumberTitle','off','Name','Option Selection','Position',[750,300,460,520]);
panel1 = uipanel(fig,'Title','Options','Position',[140,80,200,280]);
bg = uibuttongroup(fig,'Position',[140 290 200 51],'SelectionChangedFcn',@bselection);
rb1 = uiradiobutton(bg,'Position',[5 30 100 20],'FontWeight','bold');rb1.Text = 'Option 1';
rb2 = uiradiobutton(bg,'Position',[5 10 100 20],'FontWeight','bold');rb2.Text = 'Option 2';
Opt1_label = uilabel(panel1,'text','Option 1','Position',[5 180 100 20],'FontWeight','bold');
Opt1_field = uieditfield(panel1,'text','Position',[5 160 100 20]);
Opt2_label = uilabel(panel1,'text','Option 2','Position',[5 60 250 20],'FontWeight','bold');
Opt2_field = uitextarea(panel1,'Position',[5 15 190 45]);

function bselection(bg,Opt1_label,Opt1_field,Opt2_label,Opt2_field)
if bg.Buttons(1).Value == 1
    Opt1_label.Enable=1;
    Opt1_field.Enable=1;
    Opt2_label.Enable=0;
    Opt2_field.Enable=0;
elseif bg.Buttons(2).Value == 1
    Opt1_label.Enable=0;
    Opt1_field.Enable=0;
    Opt2_label.Enable=1;
    Opt2_field.Enable=1;
end
end

The enable/disable if statement works standalone, but I cannot figure out how to get it to work as a callback. Option 2 is not disabled even though option 1 is selected first by default, and if I select another radio button, either nothing changes or I will get an error saying the Enable handle isn't found.

Any ideas are much appreciated Thanks in advance!

1 Answers

You have configured your function bgselection() to be a callback function for a UI element. Callback functions have to have specific input arguments: the first must be the handle of the object that called the function, and the second must be "eventData" for the callback event. So in your function, the argument Opt1_label is being treated as a eventData variable. Since it does not have the information expected in that variable, there is an error. So if you change your function definition to:

function bselection(bg,eventData,Opt1_label,Opt1_field,Opt2_label,Opt2_field)

it will work fine. You can see the documentation for this here.

Also, the eventData has some useful information, such as the label of the button that is selected. Try adding disp(eventData) to the function to see what is included there.

Related