Mega Code Archive

 
Categories / Delphi / OOP
 

Creating class properties

Title: Creating class properties Question: This article demonstrates how to add a class property to a new component like the Font property on most components. Answer: The following example declares a class, TMyClassProp which contains several fields including an enumerated type field. Notes: 1. PropertyObject - must be of type TPersistant or a descendant class of TPersistant. 2. Must create an instance of this TMyClassProp in the Create of the component. unit SubClass; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type { First Create a enumerated list of elements then create a set of these elements } TEnumList = (Mom, Dad, Sibling, Sister, Brother); TEnum = set of TEnumList; { Here is the Class Object we want to use as a property in our Component. It has 4 properties, a Boolean, Word, String, and the enumerated type. } TMyClassProp = class(TPersistent) FBool: Boolean; FWord: Word; FString: String; FEnum: TEnum; published property HaveCar: Boolean read FBool Write FBool; property Age: Word read FWord write FWord; property Name: String read FString write FString; property Relation: TEnum read FEnum write FEnum; end; // TMyClassProp { Now create the component which will contain a property of type TMyClassProp.} TMyComponent = class(TComponent) FEnum: TEnum; { Enumerated type, just for fun } FSubClass: TMyClassProp; { The Class Property we want } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Relation: TEnum read FEnum write FEnum; property Relative: TMyClassProp read FSubClass write FSubClass; { Published declarations } end; procedure Register; implementation { Override Create, to create an instance of the Class property. This is required. } constructor TMyComponent.Create(AOwner: TComponent); begin inherited; FSubClass := TMyClassProp.Create; end; { Override Destroy to perform house cleaning. } destructor TMyComponent.Destroy; begin FSubClass.Free; inherited; end; procedure Register; begin RegisterComponents('Samples', [TMyComponent]); end; end.