How to keep the slider position the same after retrieving its value?

7 views (last 30 days)
Nora Khaled
Nora Khaled on 2 Mar 2020
Commented: Adam on 3 Mar 2020
Hi !
I am using a slider and a pushbutton to get the value from the slider.
but each time the push button is pressed the position of the slider would change.
Is there a way to keep it in the same position?
Example:
if the slider was moved to the middle, then the push button was pressed the value I get is 5.
and the slider position return to the beginning.
then if I push the button again (without changing the position)
I also get the value 5 which is what I want, my problem is with the change of the slider position.
The pushbutton code:
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global slider_input;
global roadA;
if isempty(roadA)
slider_input=10;
else
slider_input=10-roadA;
end
guidata(hObject, handles);
uiresume();
Thank you!
  3 Comments
Adam
Adam on 3 Mar 2020
You should take a read of this:
to properly understand how to communicate within a GUI, especially a GUIDE GUI like this one.
For starters, don't use global variables. They alone mean that what you write in this function suddenly has the potential to impact goodness knows where in your code (and is likely the root cause of this problem since nothing in this function explicitly changes the slider value).
Also
guidata( hObject, handles )
does nothing here. Yes, it is a key component of the data sharing mentioned in that link, but only when you understand its purpose. It is used to write the handles struct back into the GUI so that in future callbacks that is the version of handles that will be passed on. In your case here you do not make any changes to the handles structure so there is not need to call this.

Sign in to comment.

Answers (1)

John Petersen
John Petersen on 2 Mar 2020
It's not a great idea to be using any globals in here.
My guess is that roadA has the value of 5 and that's why slider_input = 10-roadA = 5;
Read the slider value using
slider_input = get(hObject,'Value');
Then use it as needed such as set_param for changing the value in a simulink block.

Community Treasure Hunt

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

Start Hunting!