问题
I would like to create a TTabsheet which has to be create during run time. The TTabSheet has several components, but all of these components will be identical on every tab. Is it possible to create a "type" variable which will create these tabs every time?
Thanks
回答1:
Yes. You could create inherited class from TTabSheet
TCustomTabSheet = class(TTabSheet)
public
constructor Create(AOwner : TComponent); override;
public
FTestButton : TButton;
end;
constructor TCustomTabSheet.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FTestButton := TButton.Create(Self);
FTestButton.Parent := Self;
FTestButton.Left := 1;
FTestButton.Top := 1;
FTestButton.Width := 20;
FTestButton.Heigth := 10;
FTestButton.Caption := 'Cool button!';
FTestButton.Name := 'TestButton';
end;
You could also create a frame (TFrame) with your custom controls in design time and host it instances to all new tabs.
回答2:
Just for the fun of it, here's a snippet of code I use periodically to add a tabsheet to a TPageControl that has a TMemo on it. This would be used, for example, if you've got a form that is used for editing text files. You'd call this to add a new tab with the filename as caption, then load the memo's .Line
property from the file's contents.
function TMy_form.add_ts_mmo( ntbk : TPageControl; caption : string ) : TTabSheet;
var mmo : TMemo;
begin
Result := TTabSheet.Create(self);
Result.PageControl := ntbk;
Result.Caption := caption;
mmo := TMemo.Create(self);
Result.Tag := Integer(mmo);
mmo.Parent := Result;
mmo.Font.Name := 'Courier New';
mmo.Font.Size := 10;
mmo.Align := alClient;
mmo.ScrollBars := ssBoth;
mmo.WordWrap := true;
end;
You call it by giving it the PageControl you want it to be added to, and a caption that's used in the tab.
var
ts : TTabSheet;
. . .
ts := add_ts_mmo( myPageControl, ExtractFileName( text_file_nm ) );
Note that I save the new memo's pointer in ts.Tag
so I can easily get to it later on through a cast.
TMemo(ts.Tag).Lines.LoadFromFile( text_file_nm );
No subclassing is required. You can create any other components you might want on the tabsheet as well, after the Result.Caption := caption
line. Just be sure to set their .Parent
property to Result
.
The PageControl can be created either at design time or run-time.
来源:https://stackoverflow.com/questions/27188910/how-to-dynamically-create-customized-tabsheet-runtime