2014-09-22 15 views
1

我試圖用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

+0

你有沒有設置'OwnerDraw'屬性爲真? – TLama 2014-09-22 12:58:29

+0

我運行此代碼,並在白色背景上獲得黃色文本。你看到了什麼。 – 2014-09-22 13:38:33

+0

我看到了windows的默認顏色,就好像'CustomDraw'事件根本不存在。 (在Delphi 2009/Win7/Windows經典主題中測試過) – 2014-09-22 13:47:34

回答

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

如果您將ViewStyle設置爲vsList,那麼您已啓動並正在運行。

+1

-1設置['OwnerDraw'](http://docwiki.embarcadero.com/Libraries/en/Vcl.ComCtrls.TListView.OwnerDraw)不是這裏所需要的。它與自定義繪畫事件無關。我鏈接到上面的文檔說:*指定列表視圖是否收到一個OnDrawItem事件。 將OwnerDraw設置爲True並將ViewStyle設置爲vsReport,以便允許列表視圖接收OnDrawItem事件,而不是默認呈現列表項。 注意:此屬性獨立於OnCustomDraw,OnCustomDrawItem,OnAdvancedCustomDraw和OnAdvancedCustomDrawItem事件。* – 2014-09-22 13:42:41

+1

關於您的編輯。你完全改變了答案。最好刪除第一個答案,然後添加一個新答案。整理選票。但提問者想要使用vsReport。 – 2014-09-22 18:26:04

+1

關於你的評論@david它更好地回答這個問題,而不是評論他人的答案。如果你沒有任何建設性的話,那麼最好避免這個問題。 – 2014-09-23 04:13:23

相關問題