Using uigetdir as callback for a pushbutton, crashes due to weird, invalid arguments

梦想的初衷 提交于 2019-12-25 07:20:01

问题


I am trying to create a simple "browse" button on a Matlab (R2016a) GUI. My code is something like:

hd = dialog;
hb = uicontrol('parent',hd,'style','pushbutton','string','browse',...
'callback',@uigetdir);

The callback function uigetdir has 2 optional arguments STARTPATH, TITLE. In principle I could pass these on my callback by concatenating them with the function handle on a cell array, such as

hd = dialog;
hb = uicontrol('parent',hd,'style','pushbutton','string','browse',...
'callback',{@uigetdir,'myStartPath','myTitle');

Whether my browse button calls uigetdir with or without the optional arguments, it will crash. Different errors, same reason: uicontrol decides to include 2 uncalled-for, weird variables (containing UI properties) as arguments to the callback function, and uigetdir doesn't know what to do with them.

Does this mean I cannot use uigetdir (or pretty much any other built in function) as a callback function in a GUI? There must be a solution besides writing a custom function, no?


回答1:


By default all uicontrol objects are passed two input arguments:

  • The uicontrol handle itself
  • An object containing information specific to the event.

When you define a callback by simply appending @ to a function name to create a function handle, these two arguments are automatically passed to the function.

You can instead craft your anonymous function to accept two input arguments and call uigetdir with no input arguments, effectively ignoring the default callback inputs.

set(hb, 'Callback', @(s,e)uigetdir())

If you want to pass a start path and a title you can pass those to uigetdir from within the anonymous function.

set(hb, 'Callback', @(s,e)uigetdir('mystartpath', 'mytitle'))


来源:https://stackoverflow.com/questions/38855223/using-uigetdir-as-callback-for-a-pushbutton-crashes-due-to-weird-invalid-argum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!