Delphi:列表视图中的Canvas.FillRect

max*_*fax 0 delphi listview brush rect fill

在更改列表视图的SubItem文本时,我需要刷整并填充整行:

procedure TForm1.ListViewDrawItem(Sender: TCustomListView;
  Item: TListItem; Rect: TRect; State: TOwnerDrawState);
begin
  if Item.SubItems[2]='Done'
   then
  begin
    Sender.Canvas.Font.Color := clBlack;
    Sender.Canvas.Brush.Color := clGreen;
    Sender.Canvas.Brush.Style := bsSolid;
    Sender.Canvas.FillRect(Rect);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

但是Sender.Canvas.FillRect(Rect)将仅填充SubItem的Rect.如何填满整行?

这个问题是在Delphi的基础上提出的:如何在CustomDrawItem的List View中绘制小图标

谢谢!

And*_*and 5

首先,如果你有三列,它们是Caption,SubItems[0]SubItems[1],还记得吗?没有SubItems[2]!

无论如何,这很容易.您只需要对旧代码进行非常非常小的修改.

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 := clBlack;
    Sender.Canvas.Brush.Color := clLime;
  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;
  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;
end;
Run Code Online (Sandbox Code Playgroud)

截图http://privat.rejbrand.se/TListViewCustomDrawIconSel.png

请特别注意我使用clLime而不是clGreen,因为背景clBlack上的文字clGreen看起来很可怕!不过,您可以考虑clWhiteclGreen背景上使用文本:

截图http://privat.rejbrand.se/TListViewCustomDrawIconSel2.png

针对评论进行更新:

要更改列表视图的第三列,它不会这样做

procedure TForm1.FormClick(Sender: TObject);
begin
  ListView1.Items[3].SubItems[1] := 'Done';
end;
Run Code Online (Sandbox Code Playgroud)

实际上,Windows并不知道一列的数据会影响整行的外观! 最简单的解决方法是告诉Windows在更改值后重新绘制整个控件 更好:只需告诉Windows重绘当前行:

procedure TForm1.FormClick(Sender: TObject);
begin
  ListView1.Items[3].SubItems[1] := 'Done';
  ListView1.Items[3].Update;
end;
Run Code Online (Sandbox Code Playgroud)

  • 你的绿色行看起来像一个选择,所以设计可能不是最佳的.如果你想绘制真正的选择,你需要为此编写额外的代码,因为我们是所有者绘制控件.这意味着我们对Windows说,"嘿,不要在客户区绘制任何东西,我会这样做".因此,Windows什么也没有,甚至没有选择和鼠标悬停效果.如果你需要,你必须自己写.上面的代码既没有选择也没有鼠标悬停效果. (2认同)