How can I force a slider UIcontrol object in GUIDE to move in discrete steps?

15 visualizaciones (últimos 30 días)
I would like to create a slider UIcontrol object that moves only to integer values between a range of 1 and 16. By default, the slider can be dragged to non-integer values. How can I force the slider to move to only integer values?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 5 de Sept. de 2018
Editada: MathWorks Support Team el 5 de Sept. de 2018
In order to create a slider UIcontrol object that moves to only integer values, we would need to ensure that 1) clicking the arrow keys and 2) dragging the slider, both move the slider to an integer position. The following illustrate how to do this:
1) Clicking the arrow keys
In order to ensure that clicking the arrow keys moves slider one unit, we can set the minimum step size of the slider to be 1/(MaxSliderValue-MinSliderValue). In this particular example, you would set it as 1/15 units. This can be set by using the 'SliderStep' property of the slider object. In the example code, we have set the 'SliderStep' to [1/15 1]. This means that clicking on the left or right arrow would move the slider 1/15 normalized units (or 1 integer value) and clicking the space between the slider and the arrows would move it completely to one side (this is set by the second element of 'SliderStep', which is equal to 1 in this example).
2) Dragging the slider
In order to ensure that dragging the slider moves it to an integer position, we can round off the value pointed by the slider in the callback function, and also set the position of the slider to this rounded off value.
The following example code illustrates this:
function myslider
figure;
sld = uicontrol('Style', 'slider',...
'Min',1,'Max',16,'Value',8,...
'Units', 'Normalized',...
'Position', [0.3 0.48 0.4 0.04],...
'Callback', @print_val,...
'SliderStep', [1/15 1]);
end
function print_val(hObject,callbackdata)
newval = hObject.Value; %get value from the slider
newval = round(newval); %round off this value
set(hObject, 'Value', newval); %set slider position to rounded off value
disp(['Slider moved to ' num2str(newval)]); %display the value pointed by slider
end
This screenshot shows the generated GUI and the output at the command line after playing around with the slider for a while:

Más respuestas (0)

Categorías

Más información sobre Migrate GUIDE Apps en Help Center y File Exchange.

Productos


Versión

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by