Trigger event for graphic handle object?

2 ビュー (過去 30 日間)
Bruno Luong
Bruno Luong 2021 年 7 月 19 日
コメント済み: Bruno Luong 2024 年 5 月 20 日
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'.

採用された回答

Satwik
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!
  1 件のコメント
Bruno Luong
Bruno Luong 2024 年 5 月 20 日
Thanks.
To be honest I can't remember the context why I need notify on hraphic handle object three year earlier (2021).
.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by