Trigger event for graphic handle object?

조회 수: 7 (최근 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 CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by