Is it possible to create an object in a GUI whose position I can define by the cursor position (drag when clicked) by setting its 'Position' property to whatever the cursor position is? What function should I be using?
You can use the SELECTMOVERESIZE function to turn on moving and resizing for your GUI object. Then you can just click and drag the object with the mouse. It's as simple as this:
set(hObject,'ButtonDownFcn','selectmoveresize');
What's not so simple is if your GUI object is a uicontrol object, in which case you will have to disable the object by setting the 'Enable'
property to 'off'
or 'inactive'
in order to have the 'ButtonDownFcn'
function execute instead of the 'Callback'
function. This is true even if you haven't defined a callback for the object.
You will also probably need to add a means to your GUI to turn the moving and resizing of the object on and off, perhaps an extra button or a menu item you can select. To show how you could do this with a push button, here's a simple example that creates a figure with an editable text box and a push button that turns on and off the ability to move and resize the editable text box:
function GUI_example
hFigure = figure('Position',[100 100 200 200],... %# Create a figure
'MenuBar','none',...
'ToolBar','none');
hEdit = uicontrol('Style','edit',... %# Create a multi-line
'Parent',hFigure,... %# editable text box
'Position',[10 30 180 160],...
'Max',2,...
'String',{'(type here)'});
hButton = uicontrol('Style','pushbutton',... %# Create a push button
'Parent',hFigure,...
'Position',[50 5 100 20],...
'String','Turn moving on',...
'Callback',@button_callback);
function button_callback(hSource,eventData) %# Nested button callback
if strcmp(get(hSource,'String'),'Turn moving on')
set(hSource,'String','Turn moving off'); %# Change button text
set(hEdit,'Enable','inactive',... %# Disable the callback
'ButtonDownFcn','selectmoveresize',... %# Turn on moving, etc.
'Selected','on'); %# Display as selected
else
set(hSource,'String','Turn moving on'); %# Change button text
set(hEdit,'Enable','on',... %# Re-enable the callback
'ButtonDownFcn','',... %# Turn off moving, etc.
'Selected','off'); %# Display as unselected
end
end
end
Note: although the documentation lists the 'Selected'
property as read-only, I was able to modify it without a problem. It must be a typo in the documentation.
You can create an invisible axes in your GUI, and plot whatever objects you want in there. Then, you can use DRAGGABLE from the File Exchange to allow for dragging objects all over the place.
© 2022 - 2024 — McMap. All rights reserved.