Deleted passed UIFigure handle on bootup of MATLABWindow

6 次查看(过去 30 天)
When running the following script, on the first bootup of MATLABWindow for the uifigure, sometimes the figure handle will be deleted before it can be used: the script will show "handle to deleted Figure". Moving the mouse over the window activates the error.
It doesn't happen everytime. I have found the most reliable way to produce this result is to run the script, quit out of MATLABWindow, clear the variables, and run it again.
What is going on? Is this a bug? How could I avoid it? (I want to preserve the callbacks, something about the persistence, and the one-time initialization of S. This script is a very pared down version of a more complete tool.)
clear S
S.fig= uifigure;
set(S.fig,'WindowButtonMotionFcn',{@Callback, S})
function Callback(~,~, s)
persistent S
if isempty(S)
S= s;
end
S.fig
end
  1 个评论
Jan
Jan 2022-4-18
What does this mean: " on the first bootup of MATLABWindow for the uifigure"?
Please post the complete error message, which shows, in which line the problem occurs.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2022-4-18
If you run this script twice, the persistent variable S contains the handle of the former figure.
Workaround:
clear S
S.fig = uifigure;
set(S.fig,'WindowButtonMotionFcn', {@Callback, S})
function Callback(~, ~, s)
persistent S
if isempty(S) || ~isequal(S, s)
% ^^^^^^^^^^^^^^^^^ Replace formerly stored figure handle
S = s;
end
S.fig
end
Or start with clearing the callback also:
clear S
clear Callback
This resets the persistent variable.
Storing the figure handle persistently in a callback function seems to be a bad idea. The figure handle is the first input of the WindowButtonMotionFcn in every case. Performing some setup in the first call should not be hidden in this callback, but in a code block for initialising the function. If you want to know, if a figure was setup up before, use a flag in the figure's UserData or ApplicationData instead of a persistent variable in the callback. Then you get no confusion between mutliple instances of the figure.
  1 个评论
Zel Hurewitz
Zel Hurewitz 2022-4-18
Thanks so much! The initialization step worked. Here is my modified code which has run consistently without dropping the handle.
clear S Callback
fig= uifigure;
S.ax= uiaxes(fig);
Callback([],[],S,'initialize')
set(fig,'WindowButtonMotionFcn',{@Callback, [], 'move'})
function Callback(~,~, s, flag)
persistent S
switch flag
case 'initialize'
S= s;
case 'move'
S.ax
end
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Develop uifigure-Based Apps 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by