动态创建具有相同对齐的按钮

时间:2013-07-31 15:26:58

标签: delphi button dynamic alignment panel

我是这个德尔福的新手。我被赋予了动态创建按钮的任务。但问题是所有按钮必须以适合整个屏幕的方式对齐。即,如果创建了10个按钮,则应填充整个屏幕。或者如果给出9,则应该存在9并填入屏幕。有可能吗?我到处尝试搜索。但是很无奈。

请尽可能帮助我。一个很好的例子也很受欢迎,因为我之前提到过我对此非常陌生。我在这里做的代码如下。

procedure TfrmMovieList.PnlMovieClick(Sender: TObject);
begin
  for i := 0 to 9 do
  begin
    B := TButton.Create(Self);
    B.Caption := Format('Button %d', [i]);
    B.Parent := Panel1;
    B.Height := 23;
    B.Width := 100;
    B.Left := 10;
    B.Top := 10 + i * 25;
  end;
end;

1 个答案:

答案 0 :(得分:1)

这看起来对我来说是可行的:

procedure TForm1.CreateButtons(aButtonsCount, aColCount: Integer; aDestParent: TWinControl);
var
  rowCount, row, col, itemWidth, itemHeight: Integer;
  item: TButton;
begin
  if aColCount>aButtonsCount then
    aColCount := aButtonsCount;
  rowCount := Ceil(aButtonsCount / aColCount);
  itemHeight := aDestParent.Height div rowCount;
  itemWidth := aDestParent.Width div aColCount;
  for row := 0 to rowCount-1 do begin
    for col := 0 to aColCount-1 do begin
      item := TButton.Create(Self);
      item.Caption := Format('Button %d', [(row*aColCount)+col+1]);
      item.Left := itemWidth*col;
      item.Top := itemHeight*row;
      item.Width := itemWidth;
      item.Height := itemHeight;
      item.Parent := aDestParent;
      Dec(aButtonsCount);
      if aButtonsCount=0 then
        Break;
    end; // for cols
  end; // for rows
end;

使用的一个例子是:

procedure TForm1.Button1Click(Sender: TObject);
begin
  CreateButtons(10, 4, Panel1);
end;

Ceil 功能需要使用单位数学

该方法接收按钮计数和列数以计算行数。它还接收按钮所在的目标父级。