Glen Morse
Glen Morse

Reputation: 2593

Adding label to custom component as a child

I have a custom component TCard = class(TGraphicControl) I would like for when its created it would have a label inside it's area ex (top := 5 ) (left :=5) and it would always put a TLabel on that TCard at that spot when created.

 type
   TCard = class(TGraphicControl)
   private
      FLPower:TLabel;
      procedure SetLPower(value:TLabel);
   protected
      procedure Paint; override;
   public
    property LPower: TLabel read FLpower write SetLPower;


...

 constructor Tcard.Create(AOwner: Tcomponent);
 begin
   inherited Create(AOwner);
   FLPower := TLabel.Create(self);
end

  procedure TCard.SetLPower(value: TLabel);
  begin
    FLPower.Assign(value);
  end;

  procedure Tcard.Paint;
  begin
      FLPower.Left := 5;
      FLPower.Top := 5;
  end;

I know what i have is not right, but i wanted to show something. Also if it helps, i plan in future to beable to do TCard.LPower.Caption := inttostr(somenumber); So if you can work that in then bonuse .. if not i can figure that out later..but wanted to give a heads up incase something you suggest would not work due to that. Thanks glen

Upvotes: 0

Views: 959

Answers (1)

David Heffernan
David Heffernan

Reputation: 612894

A TGraphicControl cannot be used as a parent control and so you cannot adopt this approach.

A label is essentially something very simple. It's just text. You have chosen to use TGraphicControl so that implies that you are going to implement a Paint method.

So, instead of creating a label control, add a Text property of type string to your control. Then, in the Paint method, draw the text to the paint canvas. When the Text property is modified, invalidate your control so that it can be repainted.

In any case, doing it this way is the right way to do it. Adding extra controls just to draw text is over the top. You've picked the lightest weight control which is fine. Paint your card's background, and then paint any text that is required. Job done.

Upvotes: 2

Related Questions