Search code examples
delphidelphi-xe2firemonkey

How avoid that duplicate subcomponents get created when pressing ALT-F12 twice?


I want to create a component composed of a TLayout that contains a TRectangle.

The TRectangle is created inside the component's constructor and has the TLayout as its parent.

The problem: when putting this component on a form, after pressing ALT-F12 to enter the source editor for the form, then pressing it again to leave it, an extra child component (TRectangle) for the parent is created. (the TRectangle shouldn't even appear in the form text editor, which I think causes the problem)

Code for the component:

unit Problem;

interface

uses
  System.SysUtils, System.Classes, FMX.Types, FMX.Layouts, FMX.Objects;

type
  TProblem = class(TLayout)
  private
    rect: TRectangle;
  public
    constructor Create(AOwner: TComponent); override;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('FMX Problem Component', [TProblem]);
end;

{ TProblem }

constructor TProblem.Create(AOwner: TComponent);
begin
  inherited;
  rect := TRectangle.Create(nil);
  rect.Parent := Self;
end;

end.

I'm sure the answer is trivial, but would appreciate it nevertheless.


Solution

  • Use Stored := False for the rect:

    constructor TProblem.Create(AOwner: TComponent);
    begin
      inherited;
      rect := TRectangle.Create(nil);
      rect.Parent := Self;
      rect.Stored := False
    end;
    

    SetSubcomponent seems to be handled incorrectly in FireMonkey.