delphifiremonkey

Delphi (FMX) Circular Reference


I'm going insane with a "cannot create a circular dependency between components" in Delphi FMX. I'm programmatically creating controls on a form, part of which is a label, inside a grid, inside a scroll box, inside a grid.

The relevant parts of the code are:

Layout := TGridPanelLayout.Create(self);
Layout.Parent := self;
Panel := TVertScrollBox.Create(self);
Panel.Parent := Layout;
Form := TGridPanelLayout.Create(self);
Form.Parent := Panel;
FormLabel := TLabel(self);
FormLabel.Parent := Form;

It's on the last line where I'm getting the error.

Specifically, line 4387 in FMX.Types is raising the error:

procedure TFmxObject.SetParent(const Value: TFmxObject);
begin
  if Value = Self then
    Exit;
  if FParent <> Value then
  begin
    if IsChild(Value) then
       raise EInvalidOperation.Create(SCannotCreateCircularDependence);
    if FParent <> nil then
      FParent.RemoveObject(Self);
    if Value <> nil then
      Value.AddObject(Self)
    else
      FParent := Value;
  end;
end;

Does anyone know why this would be getting raised on a bunch of fresh controls?

There is some code that's not included, but it's setting up rows/columns and not relevant, but I can post if needed.

Thanks.


Solution

  • FormLabel := TLabel(self);

    This line is wrong. You are type-casting Self itself, instead of creating a new Label that Self owns. So you are indeed creating a circular reference:

    The line should be this instead:

    FormLabel := TLabel.Create(self);