Delphi:删除继承的TStringGrid

Delphi:删除继承的TStringGrid,delphi,Delphi,我想要一个自定义的StringGrid元素。 我创建了一个类: type TClassStringGrid = class(TCustomControl) ... 与 构造函数TClassStringGrid.Create(AOwner:TForm); 开始 继承创建(无); myGroupBox1:=TGroupBox.Create(AOOwner); myGroupBox1.Parent:=AOOwner; myStringGrid1:=TStringGrid.Create(se

我想要一个自定义的StringGrid元素。 我创建了一个类:

type
  TClassStringGrid = class(TCustomControl)
  ... 

构造函数TClassStringGrid.Create(AOwner:TForm);
开始
继承创建(无);
myGroupBox1:=TGroupBox.Create(AOOwner);
myGroupBox1.Parent:=AOOwner;
myStringGrid1:=TStringGrid.Create(self);
myStringGrid1.Parent:=myGroupBox1;
myStringGrid1.Options:=myStringGrid1.Options+[goEditing];
结束;
析构函数TClassStringGrid.Destroy;
开始
如果myStringGrid1为零,则开始
FreeAndNil(myStringGrid1);
结束;
如果myGroupBox1为零,则开始
破坏组件;
FreeAndNil(myGroupBox1);
结束;
//调用父类析构函数
继承;
结束;
我在Form1中创建了一个类并显示它。它起作用了。但是如果我将一些值放入StringGrid(Form1)中,然后尝试关闭Form1,我会在
freeendnil(myString rid1)中得到一个异常“元素没有父窗口”。
破坏有什么错?

如果您能为我提供任何信息,我将不胜感激。

假设您希望在此控件上的组框中显示字符串网格,那么它应该是这样的:

type
  TMyStringGrid = class(TCustomControl)
  private
    FGroupBox: TGroupBox;
    FStringGrid: TStringGrid;
  public
    constructor Create(AOwner: TComponent); override;
  end;

constructor TMyStringGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FGroupBox := TGroupBox.Create(Self);
  FGroupBox.Parent := Self;
  FStringGrid := TStringGrid.Create(Self);
  FStringGrid.Parent := FGroupBox;
end;

这样,新设计的控件就是子控件的所有者和父控件。因此,销毁会自动完成。

为什么继承创建(nil);而不是继承的创建(AOOwner)?这里的所有权被搞得一团糟。您可以创建子控件,并将它们都拥有。但你要负责摧毁这些子控件。1.将
AOwner
传递给继承的构造函数。2.将两个子控件的
nil
作为
Owner
传递。3.对析构函数中的两个子控件调用
Free
。4.从析构函数中删除所有其他代码。谢谢你的回答!我做了三个步骤:1<代码>继承的创建(AOOwner)2<代码>myGroupBox1:=TGroupBox.Create(nil)3<代码>myStringGrid1.Free但我仍然有错误。我不是这么说的,是吗。另外,您没有在表单中显示代码。也许这也是错误的。也许是时候去参观一下,并提供一份工作了。事实上,这里还有很多其他的问题。您必须从
TComponent
中引入的虚拟构造函数派生构造函数。否则,无法对控件进行流式传输。不能假定控件将有所有者。尽管可以设置子控件的父控件,但不能在构造函数中设置控件的父控件。但仅限于您的控件或其中一个子控件。如果要创建自定义字符串网格,我希望您从一个基本网格类派生。坦白地说,您离在这里工作代码还有很长的路要走。从技术上讲,字符串网格的父级是组框
type
  TMyStringGrid = class(TCustomControl)
  private
    FGroupBox: TGroupBox;
    FStringGrid: TStringGrid;
  public
    constructor Create(AOwner: TComponent); override;
  end;

constructor TMyStringGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FGroupBox := TGroupBox.Create(Self);
  FGroupBox.Parent := Self;
  FStringGrid := TStringGrid.Create(Self);
  FStringGrid.Parent := FGroupBox;
end;