-->

How do I make a StringGrid's columns fit the g

2020-07-14 12:20发布

问题:

I've been looking for a long time for a solution without any luck. Does anyone know a simple way to do that? I would like to stretch for example the second colum of my grid to fit the grid's width!

回答1:

Use the ColWidths property, like so:

with StringGrid1 do
  ColWidths[1] := ClientWidth - ColWidths[0] - 2 * GridLineWidth;

And for a more robust and flexible solution, take all fixed columns into account and parameterize the column index:

procedure SetColumnFullWidth(Grid: TStringGrid; ACol: Integer);
var
  I: Integer;
  FixedWidth: Integer;
begin
  with Grid do
    if ACol >= FixedCols then
    begin
      FixedWidth := 0;
      for I := 0 to FixedCols - 1 do
        Inc(FixedWidth, ColWidths[I] + GridLineWidth);
      ColWidths[ACol] := ClientWidth - FixedWidth - GridLineWidth;
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  SetColumnFullWidth(StringGrid1, 4);
end;


回答2:

Solution If there are more doubts command "grid.AutoFitColumns()" Where grid is one "TAdvStringGrid";

;)



回答3:

The following code works with FixedCols = 0 (to adapt for other values, ex: FixedCols = 1 ==> for Col := 1 to ...)

procedure AutoSizeGridColumns(Grid: TStringGrid);
const
  MIN_COL_WIDTH = 15;
var
  Col : Integer;
  ColWidth, CellWidth: Integer;
  Row: Integer;
begin
  Grid.Canvas.Font.Assign(Grid.Font);
  for Col := 0 to Grid.ColCount -1 do
  begin
    ColWidth := Grid.Canvas.TextWidth(Grid.Cells[Col, 0]);
    for Row := 0 to Grid.RowCount - 1 do 
    begin
      CellWidth := Grid.Canvas.TextWidth(Grid.Cells[Col, Row]);
      if CellWidth > ColWidth then
        Grid.ColWidths[Col] := CellWidth + MIN_COL_WIDTH
      else
        Grid.ColWidths[Col] := ColWidth + MIN_COL_WIDTH;
    end;
  end;
end;


回答4:

even better like this :

procedure AutoSizeGridColumns(Grid: TStringGrid);
const
  MIN_COL_WIDTH = 15;
var
  Col : Integer;
  ColWidth, CellWidth: Integer;
  Row: Integer;
begin
  Grid.Canvas.Font.Assign(Grid.Font);
  for Col := 0 to Grid.ColCount -1 do
  begin
    ColWidth := Grid.Canvas.TextWidth(Grid.Cells[Col, 0]);
    for Row := 0 to Grid.RowCount - 1 do 
    begin
      CellWidth := Grid.Canvas.TextWidth(Grid.Cells[Col, Row]);
      if CellWidth > ColWidth then
        ColWidth := CellWidth
    end;
    Grid.ColWidths[Col] := ColWidth + MIN_COL_WIDTH;
  end;
end;