Trigger event for graphic handle object?
7 次查看(过去 30 天)
显示 更早的评论
The function notify seems to be designed for user-define class. Is it possible to make it works on MATLAB graphic handle objects such as uibutton. This code
fig = uifigure;
btn = uibutton(fig);
addlistener(btn, 'PropertyAdded', @(varargin) disp('trigger'));
notify(fig, 'PropertyAdded')
returns the following error:
Returns error
Error using matlab.ui.Figure/notify
Cannot notify listeners of event 'PropertyAdded' in class 'dynamicprops'.
0 个评论
采纳的回答
Satwik
2024-5-20
编辑:Satwik
2024-5-20
Hi,
In MATLAB, the ‘notify’ function is indeed designed to work with user-defined classes that inherit from the ‘handle’ class. When you try to use notify with built-in MATLAB classes or UI components like ‘uibutton’, you're limited to the events that those classes or components explicitly define and support. Unfortunately, this means you cannot directly trigger custom events like 'PropertyAdded' on MATLAB graphics handle objects such as ‘uibutton’ without extending those classes in some way.
The error you're encountering is because the ‘uibutton’ and the ‘uifigure’ does not have an event named 'PropertyAdded' defined, and MATLAB's built-in classes do not support dynamically adding events in the same way you might add properties or methods.
While you cannot directly use notify with built-in MATLAB UI components for custom events without extending those components in some way, creating wrapper classes or custom components is a way to add custom behaviour and events to MATLAB GUI applications. Here is an example of how you could create a custom class that wraps a ‘uibutton’ and includes an event for when a custom property is added:
classdef CustomButton < handle
properties
Button matlab.ui.control.Button
CustomProperties containers.Map
end
events
PropertyAdded
end
methods
function obj = CustomButton(parent)
obj.Button = uibutton(parent);
obj.CustomProperties = containers.Map;
end
function addCustomProperty(obj, propName, propValue)
obj.CustomProperties(propName) = propValue;
notify(obj, 'PropertyAdded');
end
end
end
You can now use this class in your GUI:
>> fig = uifigure;
>> btn = CustomButton(fig);
>> addlistener(btn, 'PropertyAdded', @(varargin) disp('Custom Property added'));
>> btn.addCustomProperty('propertyName', 'value');
Hope this helps!
更多回答(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!