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

标签 delphi

我是 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/

相关文章:

delphi - 将 Blob 内容显示到 OleContainer Delphi

delphi - Delphi 2009-错误?将所谓的无效值添加到集合中

delphi - System.IOUtils.TDirectory.GetParent 奇怪的行为?

Delphi:使用TClientDataset作为内存数据集

delphi - Outlook 对象模型 - 检测电子邮件是否已发送

delphi - 从大 GIF 中检索第一帧(在最佳时间内)

windows - Delphi - 应用程序主窗体的焦点不正确

mysql - 如何通过 TDBXReader 获取数据库大小?

java - 在java中通过TCP发送数据记录

delphi - Delphi Win64 中的 Monkey 修补方法(函数)