MATLAB GUI - Select a point on a plot and run a function with a push button
조회 수: 9 (최근 30일)
이전 댓글 표시
What I want to do is to get which point the user has clicked on a given plot, and then, when he clicks on a push button, a function that receives as args the (X,Y) coordinates of that point will run. If there's no point selected on the plot, a warning msg will show, telling the user to select a point.
Is this possible?
댓글 수: 2
Geoff Hayes
2020년 5월 5일
편집: Geoff Hayes
2020년 5월 5일
Pedro - do you need the push button? Or could the user just click on a point in the axes/plot and have the code execute immediately (with that point)? Also, are you using App Designer, GUIDE or programmatically creating your GUI?
채택된 답변
Geoff Hayes
2020년 5월 5일
Pedro - in the OpeningFcn for your GUI, add a button down callback for your axes:
set(handles.axes1, 'ButtonDownFcn',@axesButtonDownCallback);
The name of the callback function will be axesButtonDownCallback. The callback will look like
function axesButtonDownCallback(hObject, eventdata)
handles.currentPoint = get(hObject,'CurrentPoint');
guidata(hObject, handles);
We get the CurrentPoint property of the axes (the hObject) and save that to a field in the handles structure. We then need to save the updated structure with guidata. This is important - if you don't do this, then the other callbacks won't have access to this fields that we've added to handles. The pushbutton callback will then be
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if ~isfield(handles, 'currentPoint') || isempty(handles.currentPoint)
fprintf('You need to choose a point!\n');
else
currentPoint = handles.currentPoint;
handles.currentPoint = [];
guidata(hObject,handles);
% do something with point
end
Note how we check to see if the 'currentPoint' field exists in the handles structure or if it does exist, whether it is empty. If either is true, then we prompt the user to choose a point (replacing the fprintf with a dialog). If we do have a point, then we extract it from the structure and then reset that field in the structure so that the user will be prompted to choose a new point next time the button is pressed. (Note that again, calling guidata is important.)
댓글 수: 10
Geoff Hayes
2020년 5월 5일
no problem! For debugging, just put breakpoints at the lines of code that you are interested in.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
