我有一个简单的指南,有两个按钮:
按钮#1绘制正弦图。
按钮#2在图表中添加一条“可移动的”垂直线。
一切正常,我可以拖动垂直线,如所需。
我现在尝试做的是记录我移动垂直线的x位置( x_history ),并将这个x_history保存到手柄(通过guidata),这样如果我停止移动这条线(鼠标释放),然后继续移动这条线(按下鼠标和移动鼠标),我可以从手柄恢复以前的x_history(通过guidata)。
我面临的问题是,每次鼠标向上移动时,手柄都会重置(!)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发布于 2017-08-07 03:07:12
使用Jan Simon的guideline,我发现了代码中缺少的内容:
在mouseDown回调( pushbutton_vertline_Callback),中的嵌套函数)中,我缺少用于获取更新的句柄副本的函数。因此,我需要将这一行添加到该嵌套函数:
handles = guidata(hObject);https://stackoverflow.com/questions/45514530
复制相似问题