Author: Tomas Rutkauskas
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.
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 StdCtrls, ComCtrls;
8
9 type
10 TForm1 = class(TForm)
11 PageControl1: TPageControl;
12 TabSheet1: TTabSheet;
13 Edit1: TEdit;
14 Edit2: TEdit;
15 Edit3: TEdit;
16 Edit4: TEdit;
17 CloneButton: TButton;
18 Memo1: TMemo;
19 procedure CloneButtonClick(Sender: TObject);
20 procedure FormCreate(Sender: TObject);
21 private
22 procedure ShowStream(ms: TMemoryStream);
23 { Private declarations }
24 public
25 { Public declarations }
26 end;
27
28 var
29 Form1: TForm1;
30
31 implementation
32
33 {$R *.DFM}
34
35 procedure TForm1.ShowStream(ms: TMemoryStream);
36 var
37 ts: TStringstream;
38 begin
39 ts := TStringstream.Create(EmptyStr);
40 try
41 ObjectBinaryToText(ms, ts);
42 ms.Position := 0;
43 memo1.text := ts.DataString;
44 finally
45 ts.free
46 end;
47 end;
48
49 procedure TForm1.CloneButtonClick(Sender: TObject);
50 var
51 ms: TMemoryStream;
52 sheet: TTabSheet;
53 S: string;
54 begin
55 ms := TMemoryStream.Create;
56 try
57 ms.WriteComponent(Tabsheet1);
58 ms.Position := 0;
59 ShowStream(ms);
60 sheet := ms.ReadComponent(nil) as TTabsheet;
61 sheet.Pagecontrol := pagecontrol1;
62 sheet.Caption := format('Tabsheet%d', [pagecontrol1.pagecount]);
63 finally
64 ms.free
65 end;
66 end;
67
68 procedure TForm1.FormCreate(Sender: TObject);
69 var
70 i: Integer;
71 c: TControl;
72 begin
73 {make the template tabsheet the owner of all controls on it}
74 for i := 0 to Tabsheet1.Controlcount - 1 do
75 begin
76 c := Tabsheet1.Controls[i];
77 Self.RemoveComponent(c);
78 Tabsheet1.InsertComponent(c);
79 end;
80 end;
81
82 initialization
83 RegisterClasses([TTabSheet, TEdit]);
84 end.
|