CJC Delphi 技巧馆's Archiver

cjc Posted at 2013-9-22 22:26

Mult Line break in listview

Mult Line break in listview


listItem.Caption:='First line'+#13#10+'SecondLine';

t is possible to have multiline strings in a standard TListView in vsReport style, but AFAIK it doesn't support varying row heights. However, if you have all rows with the same number of lines > 1 you can achieve that quite easily.

You need to set the list view to OwnerDraw mode, first so you can actually draw the multiline captions, and second to get a chance to increase the row height to the necessary value. This is done by handling the WM_MEASUREITEM message, which is sent only for owner-drawn list views.

A small example to demonstrate this:

  TForm1 = class(TForm)
    ListView1: TListView;
    procedure FormCreate(Sender: TObject);
    procedure ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
      Rect: TRect; State: TOwnerDrawState);
    procedure WMMeasureItem(var AMsg: TWMMeasureItem); message WM_MEASUREITEM;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
  ListView1.ViewStyle := vsReport;
  ListView1.OwnerDraw := True;
  ListView1.OwnerData := True;
  ListView1.Items.Count := 1000;
  with ListView1.Columns.Add do begin
    Caption := 'Multiline string test';
    Width := 400;
  ListView1.OnDrawItem := ListView1DrawItem;

procedure TForm1.ListView1DrawItem(Sender: TCustomListView;
  Item: TListItem; Rect: TRect; State: TOwnerDrawState);
  if odSelected in State then begin
    Sender.Canvas.Brush.Color := clHighlight;
    Sender.Canvas.Font.Color := clHighlightText;
  InflateRect(Rect, -2, -2);
    PChar(Format('Multiline string for'#13#10'Item %d', [Item.Index])),
    -1, Rect, DT_LEFT);

procedure TForm1.WMMeasureItem(var AMsg: TWMMeasureItem);
  if AMsg.IDCtl = ListView1.Handle then
    AMsg.MeasureItemStruct^.itemHeight := 4 + 2 * ListView1.Canvas.TextHeight('Wg');

Page: [1]
CJC好玩背单词最新版本 - 是目前最好的背单词软件,游戏好玩,功能强大,词库众多,还有真人语音,免费下载,免费试用 !

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.