Delphi: 计算一个 Column 应该有多大,不切断任何东西

Delphi: Calculate how big a Column should be, to cut nothing off

我想在 Delphi 中创建一个 StringGrid。但是如果字符串太长,字符串会被截断:

我想查看整个字符串。 String 的长度可以改变,因为用户可以自己在 StringGrid 中输入文本,所以我不能只将 ColWidths 设置为某个整数。

有没有办法调整列中最大字符串的ColWidths

您可以通过调用 TextWidth.

使用 StringGrid 的 canvas 计算每个单元格中字符串所需的宽度

这里有一个快速演示示例。为简单起见,我在代码中完成所有操作 - StringGrid 在表单的 OnCreate 中设置,但当然这仅用于演示目的。要 运行 下面的示例,请创建一个新的 VCL 表单应用程序,在表单上放置一个 TStringGrid,然后添加下面的代码。我已经对其进行了设置,因此您可以通过将该列的索引传递给函数 CalcColumnWidth 来在任何列上使用它。 const Padding 是在列的右侧添加 space - 将其调整为适合您需要的任何值。

如果用户可以编辑单元格内容,您只需在编辑后调用 CalcColumnWidth 函数重新计算列宽。

procedure TForm1.FormCreate(Sender: TObject);
begin
  StringGrid1.FixedRows := 0;
  StringGrid1.FixedCols := 0;
  StringGrid1.ColCount := 2;
  StringGrid1.RowCount := 4;
  StringGrid1.ColCount := 2;
  StringGrid1.Cells[0, 0] := '1';
  StringGrid1.Cells[1, 0] := 'Some text here';
  StringGrid1.Cells[0, 1] := '2';
  StringGrid1.Cells[1, 1] := 'Some other text here';
  StringGrid1.Cells[0, 2] := '3';
  StringGrid1.Cells[1, 2] := 'A  longer string goes here';
  StringGrid1.Cells[0, 3] := '4';
  StringGrid1.Cells[1, 3] := 'Shortest';
  CalcColumnWidth(1);
end;

procedure TForm1.CalcColumnWidth(const WhichCol: Integer);
var
  i, Temp, Longest: Integer;
const
  Padding = 20;
begin
  Longest := StringGrid1.Canvas.TextWidth(StringGrid1.Cells[WhichCol, 0]);
  for i := 1 to StringGrid1.RowCount - 1 do
  begin
    Temp := StringGrid1.Canvas.TextWidth(StringGrid1.Cells[WhichCol, i]);
    if Temp > Longest then
      Longest := Temp;
  end;
  StringGrid1.ColWidths[WhichCol] := Longest + Padding;
end;