【问题标题】:Delphi: How to make TButtons 3x3?Delphi:如何制作 TButtons 3x3?
【发布时间】:2017-03-20 11:21:25
【问题描述】:

我创建了多个 TButton。

问题是我希望创建的按钮看起来像 3x3。

如何做到这一点? 注意:按钮会更多!

我的代码:

procedure TForm1.CreateButtonsClick(Sender: TObject);
var
i:integer;
B: TButton;
begin
for i:= 1 to 7 do
  begin
    B := TButton.Create(Self);
    B.Text := Format('Button %d', [i]);
    B.Parent := Self;
    B.Height := 23;
    B.Width := 100;
    B.Position.X:=25 + i* 105;
    B.Position.Y:=70;
  end;
end;

【问题讨论】:

  • 只需使用 TGridLayout 组件并在其中添加按钮
  • Delphi 7 和 FireMonkey ???你能修复那些标签吗?至于答案,我同意 Alberto,你应该使用布局。我会选择 TGridPanelLayout。并使用 .AddObject(
  • 使用 moddiv 运算符获取行和列中的位置
  • @AlbertoMiola 我正在尝试使用 TGridLayout。请您帮我添加我的代码!
  • 以后,请不要浪费读者的时间说您正在尝试使用 TGridLayout,然后接受不使用 TGridLayout 的答案。

标签: delphi firemonkey delphi-xe8


【解决方案1】:

由于您提到使用 TGridLayout,这里有一些代码展示了如何修改您的代码以将一些 TButtons 以类似于您的屏幕截图的方式布置在一个整体中:

procedure TForm1.AButtonClick(Sender: TObject);
begin
  ShowMessage(TButton(Sender).Text);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  CreateButtons;
end;

procedure TForm1.CreateButtons;
var
  i:integer;
  B: TButton;
begin
  GridLayout1.ItemWidth := 100;
  GridLayout1.ItemHeight := 23;
  for i:= 1 to 7 do
    begin
      B := TButton.Create(Self);
      GridLayout1.AddObject(B);
      B.Text := Format('Button %d', [i]);
      B.Margins.Left := 5;
      B.Margins.Top := 5;
      B.OnClick := AButtonClick;
      //B.Parent := Self;
      //B.Height := 23;
      //B.Width := 100;
      //B.Position.X:=25 + i* 105;
      //B.Position.Y:=70;
    end;
end;

【讨论】:

  • 当我点击按钮弹出:访问违规消息
  • 那你在某处搞错了。将我更新的代码粘贴到一个新项目中 - 它非常适合我。
  • 然后调试它并找出所谓的 AV 发生在哪里。 “不工作”不是一个有用的描述。你知道如何追踪 AV 吗?
  • 好吧,在你这样做之前,尝试做任何严肃的 Delphi 开发是没有意义的,否则你只会发布“在你的职业生涯的剩余时间里不起作用2..首先,在你项目的编译器选项中,在 Compiling 下,选中 Use debug DCUsStack frames 框。在 Tools | Options 下选中 Notify on languages exception 框。然后构建(而不是编译)您的项目并让它运行直到 AV 发生 [继续]跨度>
  • @TomBrunberg:感谢您不厌其烦地确认,Tom,我很感激。
【解决方案2】:

我用 Lazarus 测试了代码(抱歉,我现在还没有 Delphi),但它应该适用于你的版本。如果不是 - 将 TopLeft 替换为 Position

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  B: TButton;
begin
  for i := 0 to 13 do
  begin
    B := TButton.Create(Self);
    B.Caption := Format('Button %d', [i + 1]);
    B.Parent := Self;
    B.Height := 23;
    B.Width := 100;
    B.Left := 25 + (i mod 3) * 105;
    B.Top := 70 + (i div 3) * 70;
  end;

end;   

【讨论】:

  • 显然现实世界的代码需要尊重字体缩放
  • 当然,完全同意你的看法。但这只是一个如何使用数学来放置元素的示例。通常我使用类似网格系统的东西来显示元素
猜你喜欢
  • 2011-01-13
  • 1970-01-01
  • 2013-04-26
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
相关资源
最近更新 更多