0
我有一个简单的指南,有2个按钮:GUIDATA更新指南中的“手柄”,使用嵌套功能
按钮#1绘制正弦图。
按钮#2为图形添加了一条“可移动”垂直线。
一切工作正常,我可以根据需要拖动垂直线。
我现在要做的是记录垂直线(x_history)的x位置,并将其保存到句柄(通过guidata),如果我停止移动该线(鼠标移动)然后继续移动该行(鼠标移动和鼠标移动),我可以从句柄(通过guidata)恢复以前的x_history。
我面对的问题是,每当鼠标移到手柄重置(!)x_history字段(删除字段),所以我松开了以前的记录x_history,当我恢复鼠标按下并移动线。
我在这里错过了什么? PS:我发现这些职位相关,但不完全适用于我的情况,因为存在嵌套函数。
谢谢,
厄尔布尔士
下面是代码:
function varargout = plot_test(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @plot_vertline_handles_OpeningFcn, ...
'gui_OutputFcn', @plot_vertline_handles_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
end
function plot_vertline_handles_OpeningFcn(hObject,~,handles,varargin)
handles.output = hObject;
guidata(hObject, handles);
end
function varargout = plot_vertline_handles_OutputFcn(~,~,handles)
varargout{1} = handles.output;
end
%% Vertline Callback
function pushbutton_vertline_Callback(hObject,~,handles) %#ok<*DEFNU>
axis_h = handles.axis_h;
vertline_h = line('parent',axis_h,'xdata',[1 1],'ydata',[-1 1],...
'ButtonDownFcn', @mouseDown);
handles.vertline_h = vertline_h;
guidata(hObject,handles)
function mouseDown(~,~)
mousedown = true;
handles.mousedown = mousedown;
guidata(hObject,handles)
end
end
%% Plot Callback
function pushbutton_plot_Callback(hObject,~,handles)
clc;
open_figs_h = get(0,'children');
close(open_figs_h(2:end));
x = -pi:0.01:pi;
y = sin(x);
fig_h = figure('units','normalized','outerposition',[0.2 0.2 .5 .5],...
'WindowButtonMotionFcn', @MouseMove, 'WindowButtonUpFcn', @MouseUp);
axis_h = axes('parent',fig_h,'position',[0.1 0.1 .8 .8]);
line('parent',axis_h,'xdata',x,'ydata',y);
handles.axis_h = axis_h;
guidata(hObject,handles);
function MouseUp(~,~)
handles = guidata(hObject);
handles.mousedown = 0;
guidata(hObject,handles);
end
function MouseMove(~,~)
try handles = guidata(hObject);catch, end
if isfield(handles,'mousedown')
mousedown = handles.mousedown;
else
mousedown = 0;
end
if mousedown
x_current = get(axis_h,'CurrentPoint');
vertline_h = handles.vertline_h;
set (vertline_h, 'XData',[x_current(1,1) x_current(1,1)]);
if isfield(handles,'x_history')
disp('Field "x_history" Exists in handles')
handles.x_history = [handles.x_history x_current(1,1)]
else
disp('Field "x_history" Does Not Exist in handles')
handles.x_history = x_current(1,1)
end
guidata(hObject,handles);
end
end
end