【问题标题】:Matlab GUI - Axes callback for mouseclickMatlab GUI - 鼠标点击的轴回调
【发布时间】:2015-04-27 20:01:32
【问题描述】:

我正在使用 matlab 编写 GUI,但不知何故,我在轴上单击鼠标的回调函数存在问题。我发现了一些类似的主题,但那里给出的解决方案无法解决我的问题。

我的代码的重要部分如下所示(第一次正常尝试使用 Axes 的 ButtonDownFcn,只要我不绘制任何东西就可以了):

function Axes_1_ButtonDownFcn(hObject, eventdata, handles)

disp('axis callback');

(第二次尝试关闭 HitTest,这个根本不起作用)

 axes(handles.Axes_1); 
 h=plot(x,y);
 set(h,'HitTest','off');
 set(gcf,'WindowButtonDownFcn','disp(''axis callback'')')
 set(h,'ButtonDownFcn','disp(''axis callback'')')

自从我关闭 HitTest 后,我​​认为即使在轴上绘制了图,点击也应该有效,但事实并非如此。有什么建议吗?

谢谢!

克劳斯

更新1:@matlabgui 我试图更改 NextPlot 以在您的示例中添加类似的内容,但它仍然无法正常工作。我认为目前我对 MATLAB/GUI 还不够熟悉,无法正确理解您的建议。

我希望这不是太要求,但如果我只是为 Axes 本身创建了一个 ButtonDownFcn(空)并绘制如下代码中的图形。单击显示图形的轴后,我必须添加到代码中以在命令窗口中显示“单击轴”(无论是单击绘图中的空白区域还是线本身)?我认为最简单的方法是在我的代码中使用一个简短的示例,然后逐步分析。

绘图代码:

axes(handles.Axes_1); 
plot(x,y);

空 bdfcn:

function Axes_1_ButtonDownFcn(hObject, eventdata, handles)

【问题讨论】:

  • 我认为你应该做类似set(hFig,'WindowButtonDownFcn',@myCallback) 的事情。换句话说,您将函数句柄分配给WindowButtonDownFcn。你试过吗?除此之外,如果可能,请尝试将每个图形句柄保存为变量。我已经看到由于 gcf 在 2014b 及以后出现的实际问题。
  • 这就是我实际在做的事情(创建一个函数作为回调)。但由于即使“disp”也不起作用,我认为简化问题会更好。 “每个图形手柄”是什么意思?类似 ax1= axes(handles.Axes_1); ?感谢您的帮助!
  • 通过保存无花果句柄 -> 我认为@patrick 意味着不要使用gcfgca 等.....(这在所有版本的 Matlab 中都是一个好主意......跨度>
  • @klaus 您应该分配一个向量figs 或一组变量fig1,fig2 ... 和图形句柄(例如fig1=figure(1);)。 gcf 获取当前图形,但是如果您在执行过程中移动了鼠标,则当前图形可能不是您想要的图形,我对 gca 没有任何问题,因为轴不太容易受到交互影响。 gca(hFig) 通常指向右轴。关于回调函数,我的意思是您在示例中使用了不正确的语法。从答案中可以看出,你必须有类似set(gcf,'WindowButtonDownFcn',@(foo,bar)disp('axis callback'))

标签: matlab matlab-guide


【解决方案1】:

以下行无法正常工作,因为 HitTest 对绘图句柄 h 关闭

set(h,'ButtonDownFcn','disp(''axis callback'')')

您需要保持轴(或将 NextPlot 属性更改为 'add'- 否则当您创建新绘图时 - 您的轴的 ButtonDownFcn 回调将被清除。

请看下面的例子:

%% This is what you have to start with
f = figure; axes ( 'parent', f, 'ButtonDownFcn', @(a,b)disp ( 'button down on axes' ) )

%% This doesn't work -> as the plot command is clearing the axes which also clears the ButtonDownFcn
f = figure; axes ( 'parent', f, 'ButtonDownFcn', @(a,b)disp ( 'button down on axes' ) ); plot ( [1:10], [1:10] );

%% The Callback is retained by changing the axes NextPlot property
f = figure; axes ( 'parent', f, 'NextPlot', 'add', 'ButtonDownFcn', @(a,b)disp ( 'button down on axes' ) ); plot ( [1:10], [1:10] );

%% This also works by using hold on.
f = figure; axes ( 'parent', f, 'ButtonDownFcn', @(a,b)disp ( 'button down on axes' ) ); hold on; plot ( [1:10], [1:10] );

更新 1

将您的代码更改为以下(未经测试的代码):

set ( handles.Axes_1, 'NextPlot', 'add' );
plot(handles.Axes_1, x,y);

% If you don't have the buttondownfcn set you add it by:
set ( handles.Axes_1, 'ButtonDownFcn', {@Axes_1_ButtonDownFcn ( handles )} );

【讨论】:

  • 我更新了我的主帖。非常感谢您投入这么多时间来帮助我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多