gpt4 book ai didi

Delphi 6 用构造函数创建新表单

转载 作者:行者123 更新时间:2023-12-03 15:17:05 26 4
gpt4 key购买 nike

我是 Delphi 新手,在动态创建新表单时遇到问题。我想使用我制作的 gui 中的 elements 属性创建新表单。这是我想要动态创建的表单:

unit AddEmployeeF;

interface

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

type
TAddEmployee = class(TForm)
GroupBox1: TGroupBox;
AddName: TLabel;
AddDept: TLabel;
AddPhone: TLabel;
AddExtension: TLabel;
AddDetails: TLabel;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
end;
var
AddEmployee: TAddEmployee;

implementation

{$R *.dfm}
constructor TAddEmployee.CreateNew(AOwner: TComponent; Dummy: Integer = 0; Detail : String);
begin
inherited Create(AOwner);
AddDetails.Caption := Detail;
end;


procedure TAddEmployee.CancelButtonClick(Sender: TObject);
begin
self.Close;
end;

end.

我不想在构造函数中再次创建所有 gui 元素,只是为了修改元素的某些属性,例如标题,但保留 gui 定义中的位置和其他属性。这是可能的?以及如何从另一个表单创建表单,就像这样? :

procedure TWelcome.SpeedButton1Click(Sender: TObject);
var
myForm :TAddEmployee;
begin
myForm := TAddEmployee.CreateNew(AOwner, Dummy, Details);

myForm.ShowModal;

end;

最佳答案

您覆盖了错误的构造函数。 TForm.CreateNew() 构造函数会绕过 DFM 流,因此所有设计时组件都不会在运行时创建。更糟糕的是,您重写的 CreateNew() 构造函数正在调用继承的 TForm.Create() 构造函数,该构造函数在内部调用 CreateNew() ,因此您将陷入无限循环,导致运行时堆栈溢出错误。

要执行您所要求的操作,请重写 TForm.Create() 构造函数,或者定义一个在内部调用 TForm.Create() 的全新构造函数。根本不涉及 TForm.CreateNew()

type
TAddEmployee = class(TForm)
...
public
constructor Create(AOwner: TComponent); override; // optional
constructor CreateWithDetail(AOwner: TComponent; Detail : String);
end;

constructor TAddEmployee.Create(AOwner: TComponent);
begin
CreateWithDetail(AOwner, 'Some Default Value Here');
end;

constructor TAddEmployee.CreateWithDetail(AOwner: TComponent; Detail : String);
begin
inherited Create(AOwner);
AddDetails.Caption := Detail;
end;

procedure TWelcome.SpeedButton1Click(Sender: TObject);
var
myForm : TAddEmployee;
begin
myForm := TAddEmployee.CreateWithDetail(AOwner, Details);
myForm.ShowModal;
myForm.Free;
end;

关于Delphi 6 用构造函数创建新表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19750813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com