在 Matlab UI 滑块上设置默认值

Setting default value on Matlab UI Slider

我在 matlab 中创建了一个最小值为 -5 且最大值为正 5 的滑块。我希望将滑块的初始值设置为 0(滑块的中间)并针对当前值要放入滑块下方的编辑框中的滑块值。我的问题是我还需要将焦点设置到滑块,以便它可以立即通过键盘操作。我试过使用 Matlab 文件交换中的 setfocus 函数,但这会导致滑块在 gui 加载时下降到 -5(因为它模拟了 [=25= 左上角的鼠标单击) ] 目的)。在 setfocus 函数调用后尝试重置滑块的值也不起作用。

下面是一些演示问题的示例代码(请注意,您还需要 setfocus .m 文件,可从以下网址获得:http://www.mathworks.com/matlabcentral/fileexchange/1898-setfocus

代码:

function slider_test

% Test script for slider. Need to maximise the figure window in order to
% see the slider. 

h.window = figure;

%% Create UI Elements

h.slider = uicontrol ('Parent', h.window, 'Style', 'slider', 'Min', -5,        'Max', 5, ...
'Value', 0, 'Position', [200, 50, 200, 50], 'SliderStep', [0.1, 0.1]);

h.TIvalue = uicontrol('Parent', h.window, 'Style', 'edit', 'String', 0,  'Position', ...
 [300, 100, 300, 100], 'FontSize', 16);


%  
%% Set callbacks

set(h.slider, 'Callback', @Slider_CallBack);
setfocus(h.slider)


    function Slider_CallBack(hObject, event)
    %Takes slider value and puts it into the editable text box
        SliderValue = get(h.slider,'Value');
        set(h.TIvalue,'String', num2str(SliderValue));
        set(h.slider,'Value', SliderValue);
    end
end

关于如何解决这个问题还有其他想法吗?

谢谢,

马丁

而不是

setfocus(h.slider);

尝试

uicontrol( h.slider );

。这对我适用于 MATLAB R2015b。应该适用于 >R13 的版本,请参阅 MATLAB Central - How do I force my GUI to give focus to a specific UICONTROL?

顺便说一句:我不太熟悉 MATLAB 中的 GUI。但是我添加了

global h;
h = struct();

in slider_test.m 否则不会初始化。