Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus Pascal - How to add a new function or property to an existing class

1 Posts
1 Users
0 Reactions
8 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

Sometimes, a class or object is missing this one little property or function we need. So how do we add a property or function to an existing class or object?

In this example I add the property "Selected" to a "TPanel".
This is a boolean property, but we could easily do with with a procedure or function as well.

In the beginning of your code (I usually place this either before the TForm definition, or in a separate unit):

  TPanel = class(ExtCtrls.TPanel)
  public
    Selected:boolean;
  end;          

Now this property exists for every TPanel in this unit and can be read or assigned to.

Note: do not forget to add the phrase "public". 

You can set the default value in the constructor like so:

TPanel = class(ExtCtrls.TPanel)
  public
    Selected:boolean;
    constructor Create(AOwner:TComponent); override;
  end;   

...

// Overriding Create Constructor - for example set some default values and event handlers
constructor TPanel.Create(AOwner:TComponent);
begin
  inherited;

  // Set initial value for example ...
  Selected := false;
end;

 Adding a function or procedure is easy as well:

TPanel = class(ExtCtrls.TPanel)
  public
    Selected:boolean;
    procedure DoSomething;
  end;   

...

procedure TPanel.DoSomething;
begin
   ...
end;

This way we do not have to abuse existing properties (eg. Tag), or fumble with all kinds of linked lists, and add convenient functions as well.


   
ReplyQuote
Share: