问题
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