Creating components at runtime - Delphi

前端 未结 9 1880
孤街浪徒
孤街浪徒 2020-12-02 15:04

How can I create a component at runtime and then work with it (changing properties, etc.)?

9条回答
  •  温柔的废话
    2020-12-02 15:25

    It depends if it is a visual or non-visual component. The principle is the same, but there are some additional considerations for each kind of component.

    For non-visual components

    var
      C: TMyComponent;
    begin
      C := TMyComponent.Create(nil);
      try
        C.MyProperty := MyValue;
        //...
      finally
        C.Free;
      end;
    end;
    

    For visual components:

    In essence visual components are created in the the same way as non-visual components. But you have to set some additional properties to make them visible.

    var
      C: TMyVisualComponent;
    begin
      C := TMyVisualComponent.Create(Self);
      C.Left := 100;
      C.Top := 100;
      C.Width := 400;
      C.Height := 300;
      C.Visible := True;
      C.Parent := Self; //Any container: form, panel, ...
    
      C.MyProperty := MyValue,
      //...
    end;
    

    A few explanations to the code above:

    • By setting the owner of the component (the parameter of the constructor) the component gets destroyed when the owning form gets destroyed.
    • Setting the Parent property makes the component visible. If you forget it your component will not be displayed. (It's easy to miss that one :) )

    If you want many components you can do the same as above but in a loop:

    var
      B: TButton;
      i: Integer;
    begin
      for i := 0 to 9 do
      begin
        B := TButton.Create(Self);
        B.Caption := Format('Button %d', [i]);
        B.Parent := Self;
        B.Height := 23;
        B.Width := 100;
        B.Left := 10;
        B.Top := 10 + i * 25;
      end;
    end;
    

    This will add 10 buttons at the left border of the form. If you want to modify the buttons later, you can store them in a list. (TComponentList ist best suited, but also take a look at the proposals from the comments to this answer)

    How to assign event handlers:

    You have to create an event handler method and assign it to the event property.

    procedure TForm1.MyButtonClick(Sender: TObject);
    var
      Button: TButton;
    begin
      Button := Sender as TButton; 
      ShowMessage(Button.Caption + ' clicked');
    end;
    
    B := TButton.Create;
    //...
    B.OnClick := MyButtonClick;
    

提交回复
热议问题