当我们将一个组件创建为一个自定义控件,并将该控件拖放到面板上时,该控件始终显示在窗体上,而不是包含的控件上。如何在Create中设置自定义控件的父级,以便当按钮被放到面板上时,按钮的父级就是面板?
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;问题在于设计时的创建,而不是运行时。这是完美的工作方式:
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;发布于 2011-06-20 17:11:53
不要在构造函数中设置Parent属性!正如其他人所说,IDE和DFM流系统将在构造函数退出后自动分配父对象。如果您需要在构造函数中执行依赖于所分配的父级的操作,则需要重新设计您的组件。覆盖虚拟SetParent()和/或Loaded()方法,并从那里执行操作。并在可以避免在设计时实际不需要的操作的地方使用if (csDesigning in ComponentState) then ...检查。
发布于 2011-06-19 23:26:33
父母应该由创建控件的人来设置。对于在设计时创建的控件,这将由流系统在创建窗体时完成。对于在运行时创建的控件,应该在创建控件时完成:
var
Control: TWinControl;
begin
Control := TGlassButton.Create(<Form or Application>);
Control.Parent := <Some other control on the form>;
end;请注意,一般而言,窗体是其上所有控件的所有者,而与父级无关。控件的父级是/应该是负责绘制它的控件:换句话说,它在视觉上位于其中的控件。即面板、TabSheet、GroupBox或其他容器。
https://stackoverflow.com/questions/6403217
复制相似问题