我正在使用GUIDE构建一个简单的MATLAB GUI。我有一个项目列表框。大多数情况下,它按预期工作,但有时(通常在使用GUIDE编辑图形之后),填充列表框会导致它消失,同时出现以下消息:
Warning: single-selection listbox control requires a scalar Value
Control will not be rendered until all of its parameter values are valid
这种行为让调试变得困难!当我逐步执行时,它按预期工作(我怀疑这是一种线程竞争或类似的东西)。此外,在相同条件下重新启动MATLAB环境后,通常会消失。
所有关于此错误的文档都是针对以前/古老版本的MATLAB(我正在使用R2010a)。
如果您有任何想法或信息,请告诉我们!
编辑:由于Mikhail的帮助,我似乎已经解决了问题。我在这里发布我的代码供将来参考。
经过大量的调试打印和疯狂点击,我发现有时当你询问列表框选择了什么时,你会得到一个空结果。这和其他问题使事情变得混乱。我将所有写入交互到列表框的操作移到了一个集中的函数中,并编写了一些测试代码来确保事情保持应该的状态。
请注意,这已在我的环境中进行了测试(在R2010a上),但并不广泛。此外,代码有点冗余,但它让我感觉很好。(即itemcount
不能小于0 ...)
function ensure_listbox_ok(handles)
%check to make sure it does not suck - ask what it has
thestrings = get(handles.listbox_files, 'String');
selection = get(handles.listbox_files, 'Value');
itemcount = length(thestrings);
betterselection = selection;
if(itemcount <= 0)
betterselection = 1;
else
if(selection > itemcount)
betterselection = itemcount;
end
end
%never use zero!!!! even if 1 is out of bounds.
if(isempty(betterselection) || betterselection <= 0)
betterselection = 1;
end
%uncomment for debug logging
%display(['Was: ' num2str(selection) ', cleaned: ' num2str(betterselection)]);
%update if we are out of bounds.
if(isempty(selection) || betterselection ~= selection)
set(handles.listbox_files, 'Value', betterselection);
end