Get handle of clicked element in GUI

6 次查看(过去 30 天)
Lask
Lask 2017-6-30
评论: Lask 2017-6-30
Hi people,
I'd like to know how to get the handle of the current axes I am clicking in GUI so another callback function can perform some action.
Thanks in advance.
  2 个评论
Adam
Adam 2017-6-30
编辑:Adam 2017-6-30
Assuming you are in some mouse click callback then you can just do
hAxes = gca;
and then do what is required with hAxes by passing it on to wherever it is wanted. I'm not putting this as an answer as I don't like suggesting anything that involves using gca in proper code, it is just the first solution that comes to my head. I assume there are better ones.
In this case though, gca should be reliable because clicking on an axes does make it the current axes (certainly as far as I am aware and from my past experience) so as long as you grab that straight away and assign it to a more reliable static handle it should behave fine.
In general though using gca is bad practice for serious code as relying on which axes happens to be the one currently in focus is brittle and prone to often surprising behaviour.
Lask
Lask 2017-6-30
That seems to fit my solution. Thanks Adam!

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-6-30
编辑:Jan 2017-6-30
Define a callback for the axes during the creation:
axes('ButtonDownFcn', @AxesCallback);
...
function AxesCallback(hAxes, EventData)
handles = guidata(hAxes);
handles.ClickedAxes = hAxes;
guidata(hAxes, handles);
end
Now handles.ClickedAxes contains the handle of the last clicked axes. Note that the callback is not triggered, if you click on an object in an axes, which catches click. Then either add the update of the "handles.ClickedAxes" in the callback of the object or disable the sensitivity of the objects by setting 'HitTest' to 'off'.
Another much simpler solution:
get(FigureHandle, 'CurrentAxes')
is the last axes, which has been drawn to or clicked in. Using the ButtonDownFcn has the advantage, that you could mark the axes visibly, e.g. by:
set(hAxes, 'Selected', 'on')
or by increasing the line width of the box. Then you need some additional code to deselect the former axes.
function AxesCallback(hAxes, EventData)
handles = guidata(hAxes);
set(handles.ClickedAxes, 'selected', 'off');
handles.ClickedAxes = hAxes;
guidata(hAxes, handles);
end
Initialize handles.ClickedAxes = [] in the OpeningFcn then.
  1 个评论
Lask
Lask 2017-6-30
I'll consider this alternative in case Adam's solution delivers surprising results. Thanks anyway Jan!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by