MATLAB 滑块回调

MATLAB Slider Callback

我使用 GUIDE 创建了一个 MATLAB Gui。在那个 GUI 中,我使用滑块来设置一些参数。我为滑块设置了一些合理的限制,但我希望用户能够将值增加到超过该初始限制。 例如,默认情况下,滑块有最小 1 和最大 10 的限制。如果它被放置在 10 并且用户单击增加的箭头,我想将最大的新值设置为 11。

为此,我想在滑块的回调函数中指定用户交互的类型。我想检查用户是否单击了滑块上的增加按钮,如果是,如果滑块处于最大值,我想更改最大值 属性.

有没有办法获取有关用户交互的信息?

我认识到,如果滑块已经是最大值,并且用户单击滑块的按钮以增加,则不会调用滑块的回调。似乎只有在实际移动滑块时才会调用回调函数。所以我猜滑块的不同按钮有单独的回调函数,我需要访问这些函数。

正如您自己发现的那样,当值已经达到最大值(或最小值)时,不会调用 Matlab 回调。

一种方法是检索滑块的 java 句柄,然后对单击滑块按钮时将触发的事件进行操作,但这会进入 'undocumented' 功能,并有可能(尽管在这种情况下很小)在未来的版本中不兼容。

解决问题的纯 Matlab 方法是使用滑块提供的另一个事件,KeyPressedFcn

例如,您可以决定使用鼠标的操作只会在设置的边界之间移动滑块值,但在键盘上点击 +- 可以覆盖 maximum/minimum 并将它们重置得更远一些。

这是在这个最小示例中实现的。将下面的代码保存到一个 slidertest.m 文件中,然后 运行 它。尝试使用鼠标导航到 min/max,然后使用 +- 键,看看它是如何工作的。如果需要,您应该能够相对简单地实现更复杂的行为。

具有可扩展边界的简单滑块:

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)