如何在创建中设置TCustomControl的父级 [英] How to set a TCustomControl's Parent In Create

查看:120
本文介绍了如何在创建中设置TCustomControl的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们将组件创建为自定义控件并将该控件放置在面板上时,该控件始终显示在窗体上,而不是包含在控件上。如何在创建中设置自定义控件的父级,以便当将按钮放在面板上时,父级就是面板吗?

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;


推荐答案

不要在构造函数中设置Parent属性!正如其他人所说,IDE和DFM流系统将在构造函数退出后自动分配父对象。如果需要在构造函数中执行依赖于已分配父项的操作,则需要重新设计组件。重写虚拟 SetParent()和/或 Loaded()方法,然后从那里进行操作。并利用 if(在ComponentState中使用cDesign)然后... 在可以避免在设计时实际上不需要的操作的地方进行检查。

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.

这篇关于如何在创建中设置TCustomControl的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆