如何调用函数,它需要在构造函数中设置控件`Parent`?

Mar*_*unu 1 delphi controls constructor access-violation

我有一个TCustomControl,我必须在构造函数中调用一些函数,这些函数要求控件具有Parent属性集.我尝试先设置它,如果我在运行时创建控件的实例,它正在工作,但是当我想在设计时将它放在窗体上时,我会遇到访问冲突.我怎样才能解决这个问题 ?

constructor TPathHolder.Create(AOwner: TComponent);
begin
 inherited;
 Parent:=TWinControl(AOwner);

 //.....that function here.... 
end;
Run Code Online (Sandbox Code Playgroud)

Dal*_*kar 5

不要在构造函数(或控件代码中的任何部分)中指定控件的父级.设置内部控件本身会干扰VCL框架在设计和运行时的工作方式.

相反,您可以覆盖SetParent方法,并在那里进行初始化.

procedure SetParent(AParent: TWinControl); override;

procedure TMyControl.SetParent(AParent: TWinControl); 
begin
  inherited;
  // put custom initialization code here
end;
Run Code Online (Sandbox Code Playgroud)

请记住,在控制生命周期内可以多次调用此方法,并且传递的AParent可以为零.