正如您自己发现的那样,当值已经处于最大值(或最小值)时,不会调用 Matlab 回调。
一种方法是检索滑块的 java 句柄,并对单击滑块按钮时将触发的事件采取行动,但这将是“未记录”功能的一半并且有机会(尽管在这种情况下很小)在未来的版本中不兼容。
解决问题的纯 Matlab 方法是使用滑块中的另一个可用事件,KeyPressedFcn。
例如,您可以决定使用鼠标的操作只会在设置的边界之间移动滑块值,但在键盘上点击 + 或 - 可能会覆盖最大值/最小值并将它们重置得更远一些.
这是在这个最小示例中实现的。将下面的代码保存到单个 slidertest.m 文件中,然后运行它。尝试用鼠标导航到最小值/最大值,然后使用+ 和- 键,看看它是如何工作的。如果需要,您应该能够相对简单地实现更复杂的行为。
带有可消耗边界的简单滑块:
function h = slidertest
h.f = figure('Position',[200 200 500 150],'Menubar','none') ;
h.sld = uicontrol('style','slider','position',[20 20 460 30],...
'Min',0 , 'Max',10 , 'SliderStep',[0.01 0.1] , 'Value', 1 , ...
'Tooltip','Use the `+` and `-` keys to override min and max boundaries') ;
h.txt = uicontrol('style','text','position',[20 80 460 40],'String','1','Fontsize',20) ;
set(h.sld,'Callback', {@sld_callback,h} ) %// set the Callback function for the slider
set(h.sld,'KeyPressFcn', {@sld_KeyPressFcn,h} ) %// set the KeyPress function for the slider
function sld_callback(hobj,~,h)
val = get(hobj,'Value') ;
set( h.txt,'String', num2str(val) )
%// put here whatever code has to be executed when you change the slider value
function sld_KeyPressFcn(hobj,evt,h)
minval = get(hobj,'Min') ;
maxval = get(hobj,'Max') ;
val = get(hobj,'Value') ;
keyIncrement = 1 ; %// define that to what suits you
switch evt.Character
case '+'
%// check if we have to increase the 'Max' before we change the value
if (val+keyIncrement) > maxval
set( hobj , 'Max' , maxval+keyIncrement ) ;
end
%// increment the value
set( hobj , 'Value' , val+keyIncrement ) ;
case '-'
%// check if we have to decrease the 'Min' before we change the value
if (val-keyIncrement) < minval
set( hobj , 'Min' , minval-keyIncrement ) ;
end
%// decrement the value
set( hobj , 'Value' , val-keyIncrement ) ;
otherwise
%// if you think about other cases ...
end
%// this is called just to update the display
%// in your case it would insure whatever callback code you have for the
%// slider is executed with the new value
sld_callback(hobj,[],h)