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

时间:2011-12-16 10:54:50

标签: delphi delphi-2010 vcl 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;

4 个答案:

答案 0 :(得分:6)

好吧,要创建TEdit,您需要执行以下操作:

创建要使用的变量。局部变量或类成员。

Edit: TEdit;

然后你构建它。

Edit := TEdit.Create(Self);

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

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

Edit.Parent := Self;

或者它可能在一个小组上。

Edit.Parent := StatusPanel;

最后,设置文本。

Edit.Text := SQLQuery1['whom']);

除了使用Caption属性而不是Text属性之外,使用标签非常相似。

你一定要设置其他属性,但我猜你已经知道该怎么做了。

答案 1 :(得分:3)

Var
  AnEdit : TEdit;
Begin
  AnEdit := TEdit.Create(self);
  AnEdit.Parent := self; // or some suitable container compoent e.g GroupBox, Panel
  AnEdit.Top := ?;
  AnEdit.Left := ?
  // any other properties you weant to set.
End;

吸引人们的是设置父母。

答案 2 :(得分:3)

您还可以直观地设计组件,对它们使用GExperts Components to Code expert,然后再次从表单设计器中删除它们。对于标签/编辑对,这给出类似

的内容
var
  Edit1: TEdit;
  Label1: TLabel;

  Edit1 := TEdit.Create(Self);
  Label1 := TLabel.Create(Self);

  Edit1.Name := 'Edit1';
  Edit1.Parent := Self;
  Edit1.Left := 344;
  Edit1.Top := 172;
  Edit1.Width := 121;
  Edit1.Height := 21;
  Edit1.TabOrder := 0;
  Edit1.Text := 'Edit1';
  Label1.Name := 'Label1';
  Label1.Parent := Self;
  Label1.Left := 296;
  Label1.Top := 176;
  Label1.Width := 65;
  Label1.Height := 17;
  Label1.Caption := 'Label1';
  Label1.FocusControl := Edit1;

大多数时候它需要一些重做(删除TabOrder行,用SetBounds替换Left / Top / ...东西,Align或你自己的逻辑,......)对于某些属性/组件它不会工作。但是你可以节省很多时间。

答案 3 :(得分:0)

用TEdit.Create(self)做 开始   父级:= ... //您要在其上放置TEdit的面板或表单的名称   文字:=“您的文字”;   //并且您可以通过提供“ Left”和/或“ Width”来设置其位置,依此类推。 结束;