在 Delphi 11 Alexandria 的 Windows 10 中的 32 位 VCL 應用程式中,我需要突出顯示TListView. 這就是我想要實作的目標:

到目前為止,如果標題包含“蘋果”或“橙子”,我已經設法僅突出顯示整個標題,使用以下代碼:
procedure TForm1.ListView1CustomDrawItem(Sender: TCustomListView; Item:
TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if System.StrUtils.ContainsText(Item.Caption, 'apples') or System.StrUtils.ContainsText(Item.Caption, 'oranges') then
Sender.Canvas.Brush.Color := clYellow
else
Sender.Canvas.Brush.Color := clWindow;
end;
...結果如下:

但是,我只需要突出顯示“apples”和“oranges”這兩個詞。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
這并不難,但是您需要將問題分成幾個小部分,然后分別解決每個部分。
首先,您需要一些機器來搜索字串,如下所示:
type
TSubstringMatch = record
Start, Length: Integer;
end;
function SubstringMatch(AStart, ALength: Integer): TSubstringMatch;
begin
Result.Start := AStart;
Result.Length := ALength;
end;
function SubstringSearch(const AText, ASubstring: string): TArray<TSubstringMatch>;
begin
var List := TList<TSubstringMatch>.Create;
try
var p := 1;
repeat
p := Pos(ASubstring, AText, p);
if p <> 0 then
begin
List.Add(SubstringMatch(p, ASubstring.Length));
Inc(p, ASubstring.Length);
end;
until p = 0;
Result := List.ToArray;
finally
List.Free;
end;
end;
然后你需要使用這臺機器分別對每個專案的每個部分進行油漆。設定串列視圖OwnerDraw = True并執行
procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
begin
if Item = nil then
Exit;
var LMatches := SubstringSearch(Item.Caption, Edit1.Text);
var LItemText := Item.Caption;
var R := Item.DisplayRect(drBounds);
var C := Sender.Canvas;
var p := 1;
for var Match in LMatches do
begin
// Draw text before this match
var S := Copy(LItemText, p, Match.Start - p);
C.Brush.Color := clWindow;
C.Font.Color := clWindowText;
C.TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfLeft]);
Inc(R.Left, C.TextWidth(S));
// Draw this match
S := Copy(LItemText, Match.Start, Match.Length);
C.Brush.Color := clYellow;
C.Font.Color := clBlack;
C.TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfLeft]);
Inc(R.Left, C.TextWidth(S));
p := Match.Start Match.Length;
end;
// Draw final part
var S := Copy(LItemText, p);
C.Brush.Color := clWindow;
C.Font.Color := clWindowText;
C.TextRect(R, S, [tfSingleLine, tfVerticalCenter, tfLeft, tfEndEllipsis]);
end;
結果:

I'll leave it as an exercise to generalise this to two or more simultaneous search phrases (like apples and oranges).
As always, custom-drawing comes with some difficulties. You need to handle selections, focus rectangles, etc. But that is a different issue.
At least I hope this should get you started.
(Disclaimer: Not fully tested.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/422347.html
標籤:
