创建复选框

时间:2012-08-23 06:28:06

标签: delphi

我正在尝试创建一些复选框,有多少是由查询的记录数决定的。此外,我需要从上一个位置设置复选框+38的位置。有人给我一些帮助吗?不知道如何创建复选框,其余的我应该能够做到......无论如何他是我迄今为止所拥有的。

var
  i, top,left : integer;
begin
......
    left := 81;
    top := 119;
    while i < qry.RecordCount do
                  begin
                    // create check box
                    // set caption of checkbox to i
                    // set checkbox loction to left + 38, top
                    // left = left+38??
                  end;

2 个答案:

答案 0 :(得分:6)

在澄清您的需求后,我建议您使用TObjectList作为复选框的容器。此列表可以拥有对象,只需通过ClearDelete从列表中删除项目即可释放它们。它还通过将获取的索引项对象类型转换为已知的类类型,提供对每个元素的简单访问。以下未经测试的伪代码中有更多内容:

uses
  Contnrs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    CheckList: TObjectList;
  public
    { Public declarations }
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CheckList := TObjectList.Create;
  // setting OwnsObjects to True will ensure you, that the objects
  // stored in a list will be freed when you delete them from list
  CheckList.OwnsObjects := True;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  // this will also release all check boxes thanks to OwnsObjects
  CheckList.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
  CheckBox: TCheckBox;
begin
  ...
  CheckList.Clear;                      // this will free all check boxes    
  for I := 0 to RecordCount - 1 do      // iterate over your recordset
  begin
    CheckBox := TCheckBox.Create(nil);  // be sure to use nil as an owner
    CheckBox.Parent := Self;            // where will be laying (Self = Form)
    CheckBox.Caption := IntToStr(I);    // caption by the iterator value
    CheckBox.Top := 8;                  // fixed top position
    CheckBox.Left := (I * 38) + 8;      // iterator value * 38 shifted by 8
    CheckBox.Width := 30;               // fixed width
    CheckList.Add(CheckBox);            // add the check box to the list
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  // this will check the first check box from the list (be careful to indexes)
  TCheckBox(CheckList.Items[0]).Checked := True;
  // this will delete 3rd check box from the list (using Clear will delete all)
  CheckList.Delete(2);
end;

答案 1 :(得分:5)

你的伪代码几乎完全翻译成Delphi代码,尽管在这里使用for循环更好:

for I := 0 to qry.RecordCount-1 do
  begin
  CheckBox := TCheckBox.Create (Self);            // the form owns the checkbox
  CheckBox.Parent := Self;                        // checkbox is displayed on the form
  CheckBox.Caption := IntToStr (I);
  CheckBox.Top := Top;
  CheckBox.Left := 81 + I*38;
  end;
顺便说一句,由于VCL内置了所有权机制,您不必释放创建的复选框。