Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I code a property with sub-properties?

Tags:

delphi

For instance, like Font. Can anyone give a very simple example? Maybe just a property with two sub-properties


Edit: I mean that when I look at Font in the object inspector it has a little plus sign which I can click to set font name "times new roman", font size "10", etc. Sorrry if I use the wrong terms, that is what I menat by "sub-properties".

like image 545
Mawg says reinstate Monica Avatar asked Sep 16 '10 08:09

Mawg says reinstate Monica


2 Answers

All you have to do is create a new published property that points to an type that has published properties.

check this code

  type
    TCustomType = class(TPersistent) //this type has 3 published properties
    private
      FColor : TColor;
      FHeight: Integer;
      FWidth : Integer;
    public
      procedure Assign(Source: TPersistent); override;
    published
      property Color: TColor read FColor write FColor;
      property Height: Integer read FHeight write FHeight;
      property Width : Integer read FWidth write FWidth;
    end;

    TMyControl = class(TWinControl) 
    private
      FMyProp : TCustomType;
      FColor1 : TColor;
      FColor2 : TColor;
      procedure SetMyProp(AValue: TCustomType);
    public
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;
    published
      property MyProp : TCustomType read FMyProp write SetMyProp; //now this property has 3 "sub-properties" (this term does not exist in delphi)
      property Color1 : TColor read FColor1 write FColor1;
      property Color2 : TColor read FColor2 write FColor2;
    end;

  procedure TCustomType.Assign(Source: TPersistent);
  var
    Src: TCustomType;
  begin
    if Source is TCustomType then
    begin
      Src := TCustomType(Source);
      FColor := Src.Color;
      Height := Src.Height;
      FWidth := Src.Width;
    end else
      inherited;
  end;

  constructor TMyControl.Create(AOwner: TComponent);
  begin
    inherited;
    FMyProp := TCustomType.Create;
  end;

  destructor TMyControl.Destroy;
  begin
    FMyProp.Free;
    inherited;
  end;

  procedure TMyControl.SetMyProp(AValue: TCustomType);
  begin
    FMyProp.Assign(AValue);
  end;
like image 63
RRUZ Avatar answered Oct 10 '22 10:10

RRUZ


What do you mean, sub-properties? There is no such thing in Delphi.

Perhaps you mean object composition where an object contains a reference to another object, for example -

interface

type
TObj1 = class
private
  FFont: TFont;  
  property Font: TFont read FFont;
end;

...

implementation

var
  MyObj: TObj1;
begin
  MyObj1 := TObj1.Create;
  MyObj1.Font.Name := 'Arial';
like image 43
Alan Clark Avatar answered Oct 10 '22 09:10

Alan Clark