with StringGrid1 do
ColWidths[1] := ClientWidth - ColWidths[0] - 2 * GridLineWidth;
为了获得更健壮和灵活的解决方案,考虑所有固定列并参数化列索引:
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;
下面的代码使用FixedCols = 0(以适应其他值,例如: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;
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;
procedure AutoSizeGridColumns(Grid: TStringGrid);
var
ACol, ARow: Integer;
GridWidth, ColWidth, ColsCount: Integer;
ColWidthDifferenceWidth, ColMinWidth, ColsSumWidth: Integer;
begin
GridWidth := Grid.Width;
ColsCount := Grid.ColCount;
ColWidth := 0;
ColsSumWidth := 0;
ColWidthDifferenceWidth := 0;
Grid.Canvas.Font.Assign(Grid.Font);
for ACol := 0 to ColsCount - 1 do
begin
for ARow := 0 to Grid.RowCount - 1 do
begin
ColMinWidth := Grid.Canvas.TextWidth(Grid.Cells[ACol, ARow]);
end;
ColsSumWidth := ColsSumWidth + ColMinWidth;
Grid.ColWidths[ACol] := ColMinWidth;
end;
if ColsSumWidth < GridWidth then
begin
ColWidthDifferenceWidth := (GridWidth - ColsSumWidth) div ColsCount - 1;
for ACol := 0 to ColsCount - 1 do
begin
Grid.ColWidths[ACol] := Grid.ColWidths[ACol] + ColWidthDifferenceWidth;
end;
end
else
begin
ColWidthDifferenceWidth := (ColsSumWidth - GridWidth) div ColsCount;
for ACol := 0 to ColsCount - 1 do
begin
Grid.ColWidths[ACol] := Grid.ColWidths[ACol] - ColWidthDifferenceWidth;
end;
end;
end;
5条答案
按热度按时间zpqajqem1#
使用
ColWidths
属性,如下所示:为了获得更健壮和灵活的解决方案,考虑所有固定列并参数化列索引:
wdebmtf22#
下面的代码使用
FixedCols = 0
(以适应其他值,例如:FixedCols = 1 ==> for Col := 1 to ...
)afdcj2ne3#
这样更好:
pkbketx94#
解决方案如果有更多疑问命令“grid.AutoFitColumns()”其中grid是一个“TAdvStringGrid”;
;)
jrcvhitl5#
签收
允许您根据容器的大小(给定内容的维度)动态调整列的大小
你可以直接粘贴,它将工作的权利开箱即用。我不解释了,我没时间。谁愿意或者谁真的需要找时间来理解这段代码,尤其是因为它非常简单