Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

delphi - How to set a TCustomControl's Parent In Create

When we create a component as a custom control and the control is dropped on a panel the control always appears on the form rather than the containing control. How do you set the parent of the custom control in Create so that when the button is dropped on panel the buttons parent is the panel?

TGlassButton = class(TCustomControl)
...
public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
...

constructor TGlassButton.Create(AOwner: TComponent);
  begin
    inherited;  ???????????
    inherited Create(AOwner); ????????????
    Parent := TWinControl( AComponent ); ??????????????
    ...
  end;

The problem is designtime creation not runtime. This works perfectly:

procedure TForm10.FormCreate(Sender: TObject);
begin
  GlassButton0 := TGlassButton.Create( Panel1 );
  GlassButton0.Parent := Panel1;
  GlassButton0.Left := 20;
  GlassButton0.Top := 6;
  GlassButton0.Width := 150;
  GlassButton0.Height := 25;
  GlassButton0.Caption := 'Created At RunTime';
end;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DO NOT set the Parent property in the constructor! As others have said, the IDE and DFM streaming systems will assign the Parent automatically AFTER the constructor has exited. If you need to perform operations in your constructor that are dependant on a Parent being assigned, then you need to re-design your component. Override the virtual SetParent() and/or Loaded() methods and do your operations from there instead. And make use of if (csDesigning in ComponentState) then ... checks in places where you can avoid operations that are not actually needed at design-time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...