首页 > 解决方案 > Delphi XE 中的 GridPanel 问题

问题描述

GridPanel 有问题!难道我做错了什么?第 2 列的第一行是调整表单大小的错误。用 Delphi XE 6 和 10.2.2 测试!将 TGridPanel 放置到窗体并将“对齐”设置为“alClient”。启动并调整表格大小。

试试下面的代码:

procedure TForm5.Button1Click(Sender: TObject);
var
  Col,Row: Integer;
  CI: TControlItem;
  Panel: TPanel;
  Rows, Cols: Integer;
begin
  GridPanel1.RowCollection.BeginUpdate;
  GridPanel1.ColumnCollection.BeginUpdate;
  GridPanel1.ColumnCollection.BeginUpdate;

  GridPanel1.RowCollection.Clear;
  GridPanel1.ColumnCollection.Clear;

  Rows := 6;
  Cols := 4;

  for Row := 1 to Rows do
  begin
    with GridPanel1.RowCollection.Add do
    begin
      SizeStyle := ssPercent;
      Value := 100 / Rows;
    end;
  end;

  for Col := 1 to Cols do
  begin
    with GridPanel1.ColumnCollection.Add do
    begin
      SizeStyle := ssPercent;
      Value := 100 / Cols;
    end;
  end;

  for Row := 0 to GridPanel1.RowCollection.Count - 1 do
  begin
    for Col := 0 to GridPanel1.ColumnCollection.Count - 1 do
    begin
      Panel := TPanel.Create(Self);
      Panel.Parent := GridPanel1;
      CI := GridPanel1.ControlCollection.Add;
      CI.Column := Col;
      CI.Row := Row;
      Panel.Caption := 'Row ' + Row.ToString + ' Col ' + Col.ToString;
      CI.Control := Panel;
    end;
  end;
  GridPanel1.ColumnCollection.EndUpdate;
  GridPanel1.RowCollection.EndUpdate;
  GridPanel1.ColumnCollection.EndUpdate;
end;

标签: delphidelphi-xedelphi-xe6gridpanel

解决方案


正如 Tom Brunberg 所指出的,设置 Panel.Parent 将它们放在控件集合中并管理事物。

  for Row := 0 to GridPanel1.RowCollection.Count - 1 do
  begin
    for Col := 0 to GridPanel1.ColumnCollection.Count - 1 do
    begin
      Panel := TPanel.Create(Self);
      Panel.Parent := GridPanel1;
      Panel.Caption := 'Row ' + Row.ToString + ' Col ' + Col.ToString;
    end;
  end;

您的代码使集合最终得到 48 个控件而不是 24 个。

form1.Caption := 'ControlCollection.Count:' + IntToStr(GridPanel1.ControlCollection.Count);

推荐阅读