uieditfield defined in classdef won't update Value

5 次查看(过去 30 天)
I'm creating an app defined within a class. I click a uibutton and within it's callback select a directory. I want to update the Value field in my uieditfield to display the path to the directory, but the text isn't appearing in the edit field.
classdef MyClass
properties
mainfig
mapgrid
dirbutton
dirdisplay
end
methods
function obj = MyClass()
obj.mainfig = uifigure();
obj.mapgrid = uigridlayout(obj.mainfig, [1 1]);
obj.dirbutton = uibutton(obj.mapgrid);
obj.dirbutton.ButtonPushedFcn = @obj.dirbutton_callback;
obj.dirdisplay = uieditfield(obj.mapgrid);
obj.dirdisplay.Placeholder = "(Choose a directory)";
end
function dirbutton_callback(obj, src, event)
thisdir = uigetdir(pwd, 'Select a folder');
if thisdir == 0
disp('No directory selected. Exiting script...')
return
end
obj.dirdisplay.Value = thisdir;
end
end
end
How do I get the displayed text to update?

回答(1 个)

Umang Pandey
Umang Pandey 2024-2-15
Hi Alex,
I understand that on clicking the button and selecting the directory, you intend to reflect the path to selected directory in the "uieditfield."
The reason behind the code not updating the "uieditfield" is because "MyClass" is a value class. It has not inherited a handle class in the class declaration. In MATLAB, the "< handle" syntax is used to indicate that a class is a handle class. A handle class allows multiple variables to refer to the same object, and changes made to the object through one variable will be reflected in all other variables that reference the same object. This is in contrast to value classes, where each variable has its own independent copy of the object.
You can incorporate the following change in your code to get it working:
classdef MyClass < handle
properties
mainfig
mapgrid
dirbutton
dirdisplay
end
methods
function obj = MyClass()
obj.mainfig = uifigure();
obj.mapgrid = uigridlayout(obj.mainfig, [1 1]);
obj.dirbutton = uibutton(obj.mapgrid);
obj.dirbutton.ButtonPushedFcn = @obj.dirbutton_callback;
obj.dirdisplay = uieditfield(obj.mapgrid);
obj.dirdisplay.Placeholder = "(Choose a directory)";
end
function dirbutton_callback(obj, src, event)
thisdir = uigetdir(pwd, 'Select a folder');
if thisdir == 0
disp('No directory selected. Exiting script...')
return
end
obj.dirdisplay.Value = thisdir;
end
end
end
To learn more about Handle classes, you can refer to the following documentation:
Hope this helps!
Best,
Umang

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by