unit VAHelpers.VAListViewHelper;

interface

uses
  Vcl.ComCtrls;

type
  TVAListViewHelper = class helper for TListView
  public
    /// <summary>Adjusts all column widths so that each column is wide enough
    ///   to display it's column header and all column values</summary>
    procedure AdjustColumnWidths;
  end;

implementation

uses
  System.Classes,
  Vcl.Forms,
  Vcl.Graphics;

procedure TVAListViewHelper.AdjustColumnWidths;
const
  HEADER_PAD = 12;
  VALUE_PAD = 14;
var
  maxCol, col, i, iMax, w: integer;
  str: string;
  max: array of integer;
  Cnvs: TCanvas;
begin
  Cnvs := GetParentForm(Self).Canvas;
  maxCol := Columns.Count;
  SetLength(max, maxCol);
  for col := 0 to maxCol - 1 do
    max[col] := Cnvs.TextWidth(Columns[col].Caption) + HEADER_PAD;
  for i := 0 to Items.Count - 1 do
  begin
    iMax := Items[i].SubItems.Count;
    if iMax >= maxCol then
      iMax := maxCol - 1;
    for col := 0 to iMax do
    begin
      if col = 0 then
        str := Items[i].Caption
      else
        str := Items[i].SubItems[col-1];
      w := Cnvs.TextWidth(str) + VALUE_PAD;
      if w > max[col] then
        max[col] := w;
    end;
    for col := 0 to maxCol - 1 do
      Columns[col].Width := max[col];
  end;
end;

end.
