delphi - 如何给节点标题的一部分加下划线或突出显示

标签 delphi virtualtreeview

我想在我的 virtualtreeview 中实现搜索功能。我想在节点中突出显示或下划线搜索到的单词。

我该怎么做? 谢谢

最佳答案

我会为 OnDrawText 事件编写一个处理程序,因为它是唯一一个(此时)您将传递节点文本的事件,该文本将在其中呈现为矩形以及为这种渲染准备的 Canvas 。这两个任务都有更合适的事件(例如用于文本背景突出显示的 OnBeforeCellPaintOnAfterItemErase,以及 OnAfterCellPaintOnAfterItemPaint > 用于文本下划线),只是它们都没有像 OnDrawText 那样提供文本渲染特定参数。

如果您的节点不是多行的,并且您不关心文本对齐、阅读方向或字符串缩短,那么您的任务可能就像以下示例之一一样简单。

1。匹配文本背景颜色

procedure TForm1.VirtualTreeDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
  Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect;
  var DefaultDraw: Boolean);
var
  BackMode: Integer;
begin
  // if the just rendered node's Text starts with the text written in a TEdit control
  // called Edit, then...
  if StartsText(Edit.Text, Text) then
  begin
    // store the current background mode; we need to use Windows API here because the
    // VT internally uses it (so the TCanvas object gets out of sync with the DC)
    BackMode := GetBkMode(TargetCanvas.Handle);
    // setup the color and draw the rectangle in a width of the matching text
    TargetCanvas.Brush.Color := clYellow;
    TargetCanvas.FillRect(Rect(
      CellRect.Left,
      CellRect.Top + 1,
      CellRect.Left + TargetCanvas.TextWidth(Copy(Text, 1, Length(Edit.Text))),
      CellRect.Bottom - 1)
    );
    // restore the original background mode (as it likely was modified by setting the
    // brush color)
    SetBkMode(TargetCanvas.Handle, BackMode);
  end;
end;

视觉输出示例:

enter image description here

2。匹配文本下划线

procedure TForm1.VirtualTreeDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
  Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect;
  var DefaultDraw: Boolean);
begin
  // if the just rendered node's Text starts with the text written in a TEdit control
  // called Edit, then...
  if StartsText(Edit.Text, Text) then
  begin
    TargetCanvas.Pen.Color := clRed;
    TargetCanvas.MoveTo(CellRect.Left, CellRect.Bottom - 2);
    TargetCanvas.LineTo(
      CellRect.Left + TargetCanvas.TextWidth(Copy(Text, 1, Length(Edit.Text))),
      CellRect.Bottom - 2
    );
  end;
end;

以及一个示例视觉输出:

enter image description here

在实际代码中,我建议预先计算这些突出显示形状,并在 OnDrawText 事件中仅进行绘制,但我会将优化留给您;我认为重点是事件本身。

关于delphi - 如何给节点标题的一部分加下划线或突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984898/

相关文章:

delphi - 如何不向 TVirtualStringTree 添加重复项?

delphi - inet_addr 对于 localhost 返回 -1

java - 进行网络连接模拟,以避免使用互联网的程序在拨号连接暂时关闭后断开连接

delphi - 如何在delphi 7项目目录中添加MSWord文件

delphi - TVirtualStringTree - 如何更改 [-]/[+] 按钮?

Delphi VirtualStringTree - 检查重复项?

delphi - 虚拟 TreeView 中可以有多个扩展节点吗?

android - delphi xe6 目标多字节代码页中不存在 Unicode 字符的映射

delphi - TPersistent + 接口(interface),Delphi

Delphi:首次单击后获取VirtualStringTree的编辑模式