例如,我为您创建了一个小项目,以帮助您了解我要实现的目标。
我有一个ModalForm,它在运行时创建了一些按钮,但是当用户按下“特殊按钮”时,我希望将窗体中的所有按钮删除,因为其他按钮将在运行时创建。这是一个示例代码
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
button : TButton;
begin
button := TButton.Create(Self);
button.Parent := Form2;
button.Caption := 'New Button';
button.Top := 50;
button.Left := 200;
Form2.ShowModal;
end;
end.
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
var
button : TButton;
begin
Form2.CloseModal;
button := TButton.Create(Self);
button.Parent := Form2;
button.Caption := 'New Button';
button.Top := 60;
button.Left := 200;
// Form2.CloseModal;
Form2.ShowModal;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
ShowModal;
end;
end.
现在在此示例中,我在表单上有3个按钮,当我单击按钮1时,我希望出现第4个按钮。但是,如果我运行我的代码,我会得到错误
“无法使可见窗口模态化”
我读到这与我没有正确关闭Form2有关。如果我关闭Form2并单击Form1中的按钮(与Form2中的按钮相同的代码),它将起作用,并且我得到第四个按钮Form2。
现在我的问题是,如何通过单击Form1中的按钮和Form2中的按钮来获得此结果。
您无需关闭并(重新)显示表单即可向其动态添加控件。在您的TForm2.Button1Click
方法中摆脱Form2.CloseModal
和Form2.ShowModal
调用,即
procedure TForm2.Button1Click(Sender: TObject);
var button : TButton;
begin
button := TButton.Create(Self);
button.Parent := Self;
button.Caption := 'New Button';
button.Top := 50;
button.Left := 200;
end;
应该管用。
顺便说一句,Form2
在按钮中添加按钮TForm1.Button1Click()
只是不好的设计,不要那样做(一种形式不应该改变其他形式)。而是在Form2中有一个创建按钮的方法,然后其他表单可以调用该函数。或重写Form2的构造函数,以便它采用一个额外的参数,该参数指示特殊按钮是否可见。
要删除按钮,您只需调用Free
它们即可。即删除表格上的所有按钮
for x := ControlCount - 1 downto 0 do begin
if(Controls[x] is TButton)then Controls[x].Free;
end;
但是,如果您具有预定义数量的按钮,最好在设计时全部创建它们,然后Visible
根据需要更改属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句