在运行时创建组件 - Delphi [英] Creating components at runtime - Delphi

查看:162
本文介绍了在运行时创建组件 - Delphi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时创建一个组件,然后使用它(改变属性等)?

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

推荐答案

取决于它是视觉还是非视觉组件。原则是一样的,但是对于每种组件,还有一些额外的注意事项。

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.

对于非可视化组件

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

对于可视化组件:

本质上,可视化组件以与非可视组件相同的方式创建。但是您必须设置一些其他属性才能使其可见。

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;

以上代码的一些解释:


  • 通过设置组件的所有者(构造函数的参数),组件在销毁表单时被销毁。

  • 设置 Parent 属性使组件可见。如果忘记了,您的组件将不会显示。 (很容易想到一个:))

  • 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;

这将在表单的左边框添加10个按钮。如果要稍后修改按钮,可以将它们存储在列表中。 ( TComponentList 是最适合的,还可以看看

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)

如何分配事件处理程序:

您必须创建一个事件处理程序方法并将其分配给事件属性。

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;

这篇关于在运行时创建组件 - Delphi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆