如何在delphi中动态创建组件,如TLabel或TEdit等

Raf*_*ari 6 delphi vcl delphi-2010 dynamic-class-creation

使用Delphi 2010

SQLQuery1.First; // move to the first record
while(not SQLQuery1.EOF)do begin
   // do something with the current record
   // What's the code should i write in this part in order to create a TEdit
   // containing the user fullname the current item.
   ShowMessage(SQLQuery1['whom']);
   SQLQuery1.Next; // move to the next record
end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 6

好吧,要创建一个,TEdit你需要做以下事情:

创建一个可以使用的变量.局部变量或类成员.

Edit: TEdit;
Run Code Online (Sandbox Code Playgroud)

然后你构建它.

Edit := TEdit.Create(Self);
Run Code Online (Sandbox Code Playgroud)

构造函数的参数是所有者.这可确保在销毁其所有者时销毁该控件.我的假设是这Self是一种形式.

现在你需要给控件一个父级.

Edit.Parent := Self;
Run Code Online (Sandbox Code Playgroud)

或者也许是在面板上.

Edit.Parent := StatusPanel;
Run Code Online (Sandbox Code Playgroud)

最后,设置文本.

Edit.Text := SQLQuery1['whom']);
Run Code Online (Sandbox Code Playgroud)

除了你使用Caption属性而不是Text属性之外,使用标签它们都非常相似.

你一定会想要设置其他属性,但我想你已经知道如何做到这一点.