Trigger event for graphic handle object?

6 visualizzazioni (ultimi 30 giorni)
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'.

Risposta accettata

Satwik
Satwik il 20 Mag 2024
Modificato: Satwik il 20 Mag 2024
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 Commento
Bruno Luong
Bruno Luong il 20 Mag 2024
Thanks.
To be honest I can't remember the context why I need notify on hraphic handle object three year earlier (2021).
.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Interactive Control and Callbacks in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by