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.FormCrea开发者_运维百科te(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;
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.
Parents should be set by whomever is creating the control. For controls created at design time, this would be done by the streaming system when the form is created. For controls created at run-time, it should be done when the control is created:
var
Control: TWinControl;
begin
Control := TGlassButton.Create(<Form or Application>);
Control.Parent := <Some other control on the form>;
end;
Please note that in general the form is the owner of all controls on it, regardless of parent-ing. The Parent of a control is / should be the control responsible for painting it: in other words the control in which it is visually located. Ie a Panel, TabSheet, GroupBox or some other container.
精彩评论