How to set a TCustomControl's Parent In Create

后端 未结 2 1350
情深已故
情深已故 2020-12-19 23:14

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 s

相关标签:
2条回答
  • 2020-12-19 23:54

    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.

    0 讨论(0)
  • 2020-12-20 00:00

    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.

    0 讨论(0)
提交回复
热议问题