2008. augusztus 17., vasárnap

Create a predefined TTabSheet at design time and call it at runtime


Problem/Question/Abstract:

I would like to create a predefinied TTabSheet (e.g. four edit boxes on the TTabsheet) at design time. And at runtime, I would like to create the predefined TTabSheet as many according to my own need. Basically my question here is how to create the TTabSheet object with four editboxes on it, and then call the tabsheet at runtime.

Answer:

You can do this using streaming. Here is a little example project. The two key points are:

the components on the template tabsheet need to be owned by the tabsheet, not the form. The formCreate method takes care of this.
all control classes used on the tabsheet need to be registered. The RegisterClasses call in the initialisation section takes care of that.


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Edit4: TEdit;
    CloneButton: TButton;
    Memo1: TMemo;
    procedure CloneButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    procedure ShowStream(ms: TMemoryStream);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.ShowStream(ms: TMemoryStream);
var
  ts: TStringstream;
begin
  ts := TStringstream.Create(EmptyStr);
  try
    ObjectBinaryToText(ms, ts);
    ms.Position := 0;
    memo1.text := ts.DataString;
  finally
    ts.free
  end;
end;

procedure TForm1.CloneButtonClick(Sender: TObject);
var
  ms: TMemoryStream;
  sheet: TTabSheet;
  S: string;
begin
  ms := TMemoryStream.Create;
  try
    ms.WriteComponent(Tabsheet1);
    ms.Position := 0;
    ShowStream(ms);
    sheet := ms.ReadComponent(nil) as TTabsheet;
    sheet.Pagecontrol := pagecontrol1;
    sheet.Caption := format('Tabsheet%d', [pagecontrol1.pagecount]);
  finally
    ms.free
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
  c: TControl;
begin
  {make the template tabsheet the owner of all controls on it}
  for i := 0 to Tabsheet1.Controlcount - 1 do
  begin
    c := Tabsheet1.Controls[i];
    Self.RemoveComponent(c);
    Tabsheet1.InsertComponent(c);
  end;
end;

initialization
  RegisterClasses([TTabSheet, TEdit]);
end.

Nincsenek megjegyzések:

Megjegyzés küldése