如何生成动态控件?

zhenww 2000-12-11 05:23:00
如何在一个动态生成的窗体中再生成一个动态控件,并将该控件显示出来?
...全文
130 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
quark 2000-12-11
  • 打赏
  • 举报
回复
//这里有一个子过程,后面付例子,一看就明白

//Designed by Quark
unit EXPro_WinControls;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, ExtCtrls, Grids;

//动态创建控件
function DynaCreateComponent(OwnerName: TComponent; CompType: TControlClass; CompName: String; V_Left,V_Top,V_Width,V_Height:Integer): TControl;

implementation

function DynaCreateComponent(OwnerName: TComponent; CompType: TControlClass; CompName: String; V_Left,V_Top,V_Width,V_Height:Integer): TControl;
begin
if (OwnerName.FindComponent(CompName)<>nil) and not(OwnerName.FindComponent(CompName) is TControl) then
begin
Result := nil;
exit;
end;
Result := OwnerName.FindComponent(CompName) as TControl;
if Result=nil then
begin
Result := CompType.Create(OwnerName);
with Result do
begin
if OwnerName is TwinControl then
begin
SetBounds(V_Left,V_Top,V_Width,V_Height);
Parent := TwinControl(OwnerName);{如果是可视构件,则显示之}
if OwnerName is TForm then TForm(OwnerName).ActiveControl := TWinControl(Result);{设置窗口焦点}
end;
end;
Result.Name := CompName;
end
else {Result<>Nil}
if not(Result is CompType) then
begin
Result := nil;
Exit;
end;
Result.Visible := True;
{对于未知数量的控件组,利用TList
var ControlList: Tlist; CreateNum: integer;
const CreateClass : TControlClass = TButton;//可以任意修改TControlClass = TEdit或TPanel等。效果一样。
var i:integer; V_Point: Pointer;
ControlList := TList.Create;
ControlList.Clear;
CreateNum := 10;
for i:=1 to CreateNum do
begin
V_Point := Pointer(DynaCreateComponent(self,CreateClass,'Button_' + IntToStr(i),0,i*20+1,60,20));//创建
ControlList.Add(V_Point);
end;
TButton(ControlList.Items[i]).Caption := 'XXXX';}
end;

end.
Hank 2000-12-11
  • 打赏
  • 举报
回复
多SAOREN的补充。

var testEdit:TEdit;

procedure Button1OnClick;
begin
testEdit:=TEdit.Create(Self);
testEdit.Parent:=self;//属于本窗体的.
//位置自己控制。
testEdit.top:=self.top-10;
testEdit.left:=self.left+10;
testEdit.width:=width-100;
testEdit.Show; //<---------------此句对可视控件要加入。
//
end;
procedure button2Onclick
begin
testEdit.Free;
end;
linkie 2000-12-11
  • 打赏
  • 举报
回复
简言之:(1)采用Application.CreateForm(TForm,FormName)方法来动态生成窗体,比如要动态生成名为Form1的普通窗体,就是Application.CreateForm(TForm,Form1),然后就用Form1.Show()方法将它显示出来,如果要设置它的相关属性就直接引用TForm的所有相关属性即可;
(2)要动态生成控件那么就得先对该类进行声明,也就是在Uses里引用相关的.pas文件,然后就和saoren的方法来生成控件。
saoren 2000-12-11
  • 打赏
  • 举报
回复
var testEdit:TEdit;

procedure Button1OnClick;
begin
testEdit:=TEdit.Create(Self);
testEdit.Parent:=self;//属于本窗体的.
//位置自己控制。
testEdit.top:=self.top-10;
testEdit.left:=self.left+10;
testEdit.width:=width-100;
//
end;
procedure button2Onclick
begin
testEdit.Free;
end;

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧