说明:展示 ListView 视其每一行 Item 的 Detail 字串长度自动调整高度(可每行高度不同)。
适用:Delphi XE7 / XE8
源码下载:[原创]ListView_自动计算行高(by龟山阿卍).zip
procedure TForm1.Button1Click(Sender: TObject); const DetailStr: array[0..2] of String = ('1234567890123456789012345678901234567890123456789012345678901234567890' ,'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' ,'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ' ); var i, r: Integer; Item1: TListViewItem; begin for i:=0 to 100 do begin Item1 := ListView1.Items.Add; r := Random(3); Item1.Detail := DetailStr[r].Substring(0, Random(DetailStr[r].Length)); Item1.Text := i.ToString; end; end; procedure TForm1.ListView1UpdateObjects(const Sender: TObject; const AItem: TListViewItem); var R: TRectF; begin if (AItem.Objects.DetailObject <> nil) and (AItem.Objects.DetailObject.Text <> '') then begin // 计算文字显示的区域 R := RectF(0, 0, AItem.Objects.DetailObject.Width, 10000); ListView1.Canvas.MeasureText(R, AItem.Objects.DetailObject.Text, AItem.Objects.DetailObject.WordWrap, [], TTextAlign.Leading, TTextAlign.Leading); // 设定高度 AItem.Height := Trunc(R.Height); end; end;
补充:计算最后一项区域并卷到最后一项
procedure TForm1.Button2Click(Sender: TObject); var R: TRectF; begin R := ListView1.GetItemRect(ListView1.Items.Count - 1); // 取得最后一项的真实区域 (不等高也能计算) ListView1.ScrollViewPos := R.Bottom; // 卷到最后 end;