如何在列表视图中更改所选项目的背景和字体颜色?

时间:2014-09-22 12:34:49

标签: delphi delphi-2009

我尝试使用OnCustomDrawItem事件更改颜色,但它没有效果。

procedure TForm1.RListCustomDrawItem(Sender: TCustomListView; Item: TListItem;
 State: TCustomDrawState; var DefaultDraw: Boolean);
begin
 if cdsSelected in State then begin
  Sender.Canvas.Brush.Color:=clRed;
  Sender.Canvas.Font.Color:=clYellow;
 end;
end;

我使用默认的TListView组件,其中3列ViewStyle设置为vsReport

2 个答案:

答案 0 :(得分:7)

字体颜色仅在代码中显示。 如果要更改背景颜色,则必须自己绘制项目和子项目,并将DefaultDraw设置为false。

这可能看起来像:

procedure TMyForm.ListView1CustomDrawItem(Sender: TCustomListView; Item: TListItem
                 ; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  rt, r: TRect;
  s: String;
  i: Integer;
  c:TCanvas;

  // Fit the rect used for TextRect
  Procedure PrepareTextRect;
  begin
    rt := r;
    rt.Left := rt.Left + 5;
    rt.Top := rt.Top + 1;
  end;

begin
  c := Sender.Canvas;
  if (cdsSelected in State) then
  begin
    c.Brush.Color := clRed;
    c.Font.Color := clYellow;
    // will get the rect for Item + Subitems in ViewStyle = vsReport
    r := Item.DisplayRect(drBounds);
    c.FillRect(r);
    // set width to get fitting rt for tfEndEllipsis
    r.Right := r.Left + TListView(Sender).Columns[0].Width;
    s := Item.Caption;
    PrepareTextRect;
    c.TextRect(rt, s, [tfSingleLine, tfEndEllipsis]);

    if TListView(Sender).ViewStyle = vsReport then
    begin // Paint the Subitems if ViewStyle = vsReport
      for i := 0 to Item.SubItems.Count - 1 do
      begin
        r.Left := r.Left + TListView(Sender).Columns.Items[i].Width;
        r.Right := r.Left + TListView(Sender).Columns.Items[i + 1].Width;
        PrepareTextRect;
        s := Item.SubItems[i];
        c.TextRect(rt, s, [tfSingleLine, tfEndEllipsis]);
      end;
    end;
    DefaultDraw := false;
  end;
end;

enter image description here

答案 1 :(得分:-1)

如果您将ViewStyle设置为vsList,那么您已启动并正在运行。