【问题标题】:Dynamically created buttons with equal alignment具有相同对齐的动态创建的按钮
【发布时间】:2013-07-31 15:26:57
【问题描述】:

我是这个 Delphi 的新手。我被赋予了动态创建按钮的任务。但问题是所有按钮都必须以适合整个屏幕的方式对齐。即,如果创建了 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;

【问题讨论】:

  • 你的代码做了什么你没想到的事情?
  • 此代码中的任何内容都没有说明作为父按钮的面板的大小。另请注意,您的原始帖子格式非常糟糕,并且没有尝试使用正确的标点符号。这对于短信或 Twitter 来说很好,但对于编程来说,标准更高。

标签: delphi button dynamic alignment panel


【解决方案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函数需要用到Math单元。

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

【讨论】:

  • 非常感谢兄弟。 !!!这对我很有用!你知道吗 ?你是救世主!!
  • 老大!我可以在动态创建的按钮或面板中显示 FilmNames 吗?即,运行此查询以在动态创建的按钮上显示 FilmNames ? QrySchedule.SQL.Add('select distinct FilmKey,FilmName from veu_ScheduleList where ShowDate='+ QuotedStr(FormatDateTime('dd-mmm-yyyy',asdate)));
  • @user2269685:我想这很简单。您只需向该方法添加一个新参数。这个新参数将是一个向量,其中包含您要为按钮设置的所有名称。该方法对查询一无所知,是什么使它更可重用。如果您更改方法的签名以接收此类参数,则可以关闭参数 aButtonsCount,因为您将能够通过数组的长度知道按钮的数量。
  • 谢谢兄弟。 !这也会帮助我!!
  • 兄弟。还有一件事 !有没有办法将这些动态创建的按钮或面板对齐在中心对齐?我的需要是,如果某个日期只有一个节目,它应该出现在中间,否则,如果它在左边对齐,那将不是一个很好的展示知道吗? !!!提前致谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2019-12-14
  • 2012-12-06
  • 1970-01-01
相关资源
最近更新 更多