CJC Delphi 技巧馆's Archiver

cjc Posted at 2013-9-22 22:26

Mult Line break in listview

Mult Line break in listview

http://stackoverflow.com/questions/1877365/add-2-line-caption-in-a-tlistview

listItem:=listView.Items.Add;
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:

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

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  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;
  end;
  ListView1.OnDrawItem := ListView1DrawItem;
end;

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

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

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

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