Delphi xe8 FMX StringGrid根据内容自适应列宽

Delphi xe8 FMX StringGrid根据内容自适应列宽。


网上的资料比较复杂,而且不是根据字体字号等设置列宽。故自己写了个function来用。


function GetColMaxDataLength(ASGrid: TStringGrid): TObject;
var
  MaxColLength,                  //列数据的最大长度
  CellLength: Single;            //单元格长度
  ACol,ARow: Integer;
begin
  with ASGrid do
  begin
    for ACol := 0 to ColumnCount - 1 do
    begin
      MaxColLength:=Canvas.TextWidth(Columns[ACol].Header);//取列头宽度
      for ARow := 0 to RowCount - 1 do
      begin
        CellLength := Canvas.TextWidth(Cells[ACol,ARow]);//取单元格宽度
        if CellLength > MaxColLength then
          MaxColLength := CellLength;
      end;
      Columns[ACol].Width := MaxColLength + 20;  //加上一个值调整列宽
    end;
  end;
end;


应用很简单,一句搞定:
GetColMaxDataLength(StringGrid1);

你可能感兴趣的:(delphi,函数,stringgrid)