Delphi:调整列表视图列的大小时的错误(在DrawItem上)

时间:2011-07-08 20:48:35

标签: delphi listview resize draw

启用列的自动调整大小,并为列表视图启用OwnerDraw。然后在from HERE下面添加代码:

procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
  Rect: TRect; State: TOwnerDrawState);
var
  i: Integer;
  x1, x2: integer;
  r: TRect;
  S: string;
const
  DT_ALIGN: array[TAlignment] of integer = (DT_LEFT, DT_RIGHT, DT_CENTER);
begin
  if SameText(Item.SubItems[1], 'done') then
  begin
      Sender.Canvas.Font.Color := clWhite;
      Sender.Canvas.Brush.Color := clGreen;
  end
  else
    if Odd(Item.Index) then
    begin
      Sender.Canvas.Font.Color := clBlack;
      Sender.Canvas.Brush.Color := $F6F6F6;
    end
    else
    begin
      Sender.Canvas.Font.Color := clBlack;
      Sender.Canvas.Brush.Color := clWhite;
    end;
  if odSelected in State then                                                    // NEW!
  begin                                                                          // NEW!
    Sender.Canvas.Font.Color := clWhite;                                         // NEW!
    Sender.Canvas.Brush.Color := clNavy;                                         // NEW!
  end;                                                                           // NEW!
  Sender.Canvas.Brush.Style := bsSolid;
  Sender.Canvas.FillRect(Rect);
  x1 := 0;
  x2 := 0;
  r := Rect;
  Sender.Canvas.Brush.Style := bsClear;
  Sender.Canvas.Draw(3, r.Top + (r.Bottom - r.Top - bm.Height) div 2, bm);
  for i := 0 to ListView1.Columns.Count - 1 do
  begin
    inc(x2, ListView1.Columns[i].Width);
    r.Left := x1;
    r.Right := x2;
    if i = 0 then
    begin
      S := Item.Caption;
      r.Left := bm.Width + 6;
    end
    else
      S := Item.SubItems[i - 1];
    DrawText(Sender.Canvas.Handle,
      S,
      length(S),
      r,
      DT_SINGLELINE or DT_ALIGN[ListView1.Columns[i].Alignment] or
        DT_VCENTER or DT_END_ELLIPSIS);
    x1 := x2;
  end;
  if odFocused in State then                                                     // NEW!
    DrawFocusRect(Sender.Canvas.Handle, Rect);                                   // NEW!
end;

如果已经自动调整大小,则主动调整倒数第二个列的大小。这是错误:

enter image description here enter image description here enter image description here enter image description here

如何预防这些错误?

谢谢!

1 个答案:

答案 0 :(得分:5)

该错误位于“comctrls.pas”中的TListColumn.GetWidth。当设置了列上的“AutoSize”时,VCL在调整列大小时检索错误的列宽,因此您将在整个列上绘制项目文本。

我看了几分钟的VCL代码并且无法弄清楚出了什么问题,但是在getter中设置值是可疑的。

无论如何,要找到解决方法,而不是

inc(x2, ListView1.Columns[i].Width);

使用它:

inc(x2, ListView_GetColumnWidth(ListView1.Handle, ListView1.Columns[i].Index));