在运行时创建组件 - Delphi [英] Creating components at runtime - 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;
对上面代码的一些解释:
A few explanations to the code above:
- 通过设置组件的所有者(构造函数的参数),当拥有的表单被销毁时,组件也会被销毁.
- 设置
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屋!