How to set default value of a slider in GUI?
13 views (last 30 days)
Show older comments
Hello,
so long story short, I have a slider and static text box. I want to be able to move the slider in order to change the value inside text box.
This is just a part of a program, so it's also essential for me to:
- set the min and max values
- set the default position of the slider. I don't want it to be in 0-position once I run the program. Say, I want it to set itself in the half of range.
That's what I have:
set(handles.slider1, 'Min', f(1));
set(handles.slider1, 'Max', f(501));
set(handles.slider1, 'SliderStep', [1/501, 10/501]);
set(handles.slider1, 'Value', f(250);
a=get(handles.slider1,'Value');
set(handles.text1,'string',num2str(a));
guidata(hObject, handles);
And it doesn't get the current position of the slider, when I run it it is constantly showing value of f(250)
Please help. Thanks in advance.
2 Comments
Stephen23
on 13 Sep 2016
Because you keep setting the value:
set(handles.slider1, 'Value', f(250);
a=get(handles.slider1,'Value');
the value is going to be exactly what you set it to: f(250).
Adam
on 13 Sep 2016
Edited: Adam
on 13 Sep 2016
If you have an array, f (or is it a function?), that you are using to supply values for your slider you might as well just use the array indices in the slider itself and only map these onto f when reporting the value for your text box.
You'll have to do some rounding anyway for when you move the slider unless you want to report values with lots of decimal places in your text box.
Answers (2)
Mischa Kim
on 13 Sep 2016
D B, please attach the entire code (see paper clip). A couple of comments:
- There is at least one round, closing bracket missing: in the fourth command and before the semi-colon.
- Where is function f defined? Is it executed? Setting breakpoints will help you pin point the problem.
0 Comments
Stephen23
on 13 Sep 2016
Edited: Stephen23
on 13 Sep 2016
Try using this minimum working example, which includes a text box and a slider that updates its value:
function main
%
bnd = [5,45]; % slider bounds
stp = [1,5]; % slider steps
htx = uicontrol('Style','text', 'Position',[300,20,100,20]);
hsl = uicontrol('Style','slider','Position',[10,20,200,20],...
'Min',bnd(1),'Max',bnd(2),'SliderStep',stp/diff(bnd),'Value',mean(bnd));
addlistener(hsl, 'Value', 'PostSet',@subfun);
%
% Callback function:
function subfun(~,~)
val = get(hsl,'Value');
set(htx,'String',num2str(val))
end
%
% Set default textbox value:
subfun()
%
end
2 Comments
Stephen23
on 13 Sep 2016
Edited: Stephen23
on 13 Sep 2016
When you read the uicontrol properties documentation you would learn that the SliderStep property must be a two-element vector, whereas you are defining it like this:
'SliderStep',(1/501)
See Also
Categories
Find more on Annotations 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!