我有一个自动调整网格中列的大小的过程,以适应该列中最大的字符串。但是,当网格中有2,000多个记录时,这会花费太多时间。有关加快此速度的任何提示?
//lstSKU = grid
procedure TfrmExcel.ResizeCol(const ACol: Integer);
var
M: Integer;
X: Integer;
S: String;
R: TRect;
begin
M:= 20;
lstSKU.Canvas.Font.Assign(lstSKU.Font);
for X:= 1 to lstSKU.RowCount - 1 do begin
S:= lstSKU.Cells[ACol, X];
R:= Rect(0, 0, 20, 20);
DrawText(lstSKU.Canvas.Handle, PChar(S), Length(S), R,
DT_LEFT or DT_VCENTER or DT_CALCRECT);
if R.Right > M then
M:= R.Right;
end;
M:= M + 15;
lstSKU.ColWidths[ACol]:= M;
end;
最佳答案
这是标准的TStringGrid / TDrawGrid吗?
您可以使用Canvas.TextWidth(S)
进行迭代,以测量每个单元格的内容宽度,保存最大的宽度,添加任何填充,然后设置Grid.ColWidths[Col] := M;
。如果需要,这将触发一次重绘。 (基本上是在做什么,而无需重复绘制操作2001次。)
procedure TfrmExcel.ResizeCol(const ACol: Integer);
var
M, T: Integer;
X: Integer;
S: String;
begin
M := 20;
for X := 1 to lstSKU.RowCount - 1 do
begin
S:= lstSKU.Cells[ACol, X];
T := lstSKU.Canvas.TextWidth(S);
if T > M then
M := T;
end;
M := M + 15;
lstSKU.ColWidths[ACol] := M;
end;
如果要同时设置单元格的宽度和高度以适应较大的字体或其他内容,请使用
TextExtent
代替TextWidth
; TextExtent
返回一个TSize
,您可以从中读取Width
和Height
。
关于performance - 加快调整网格列大小的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172437/