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

Ige*_*bam 1 delphi

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

图片

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

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

Ken*_*ite 5

您可以使用 StringGrid 的画布通过调用 来计算每个单元格中字符串所需的宽度TextWidth

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

如果用户可以编辑单元格内容,您只需要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;
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明