delphi

How to set the width value of a TMemo to get the parent size where this memo was created at runtime?


I created this class:

type
  TCustomTabSheet = class(TTabSheet)
  public
    constructor Create(AOwner : TComponent); override;
  public
    Memo : TMemo;
  end;

implementation

constructor TCustomTabSheet.Create(AOwner : TComponent);
begin
  inherited Create(AOwner);
  Memo := TMemo.Create(Self);
  Memo.Parent := Self;
  Memo.Left := 1;
  Memo.Top := 1;
  Memo.Width := Self.Width;
  Memo.Heigth := 100;
  Memo.Name := 'TestMemo';
end;

But Self.Width in the constructor has a value of 0! Why?

What I want is to create an instance for each tab sheet that contains TMemo or TStringGrid whose .Width values are the same as those of the parent.


Solution

  • At the time a TTabSheet is created, it has not been added to its parent TPageControl yet, and even if it were it doesn't know what its eventual size will be yet (TTabSheet uses Align=alClient to adjust itself to the TPageControl's size dynamically). That is why the TabSheet's Width is 0 in your constructor.

    To do what you want, set the Memo's Align=alTop and set only its Height as needed:

    constructor TCustomTabSheet.Create(AOwner : TComponent);
    begin
      inherited Create(AOwner);
      Memo := TMemo.Create(Self);
      Memo.Parent := Self;
      Memo.Align := alTop;
      Memo.Height := 100;
      Memo.Name := 'TestMemo';
    end;