1

我正在尝试创建几个复选框,多少由查询的记录数决定。我还需要从上一个位置设置复选框 +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;
4

2 回答 2

6

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

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;
于 2012-08-23T06:41:57.390 回答
5

尽管最好在for此处使用循环,但您的伪代码几乎可以直接翻译成 Delphi 代码:

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 中内置的所有权机制,您不必释放创建的复选框。

于 2012-08-23T06:39:29.677 回答