Skip to main content

TcxCustomTreeView.OnCustomDrawItem Event

Enables you to custom paint nodes.

Declaration

property OnCustomDrawItem: TTVCustomDrawItemEvent read; write;

Remarks

The OnCustomDrawItem event fires each time a node is about to be painted. You can handle this event to perform your own tree node painting. If the desired painting has been performed, set the DefaultDraw parameter to False to indicate that default painting is not needed for the processed node.

The Sender parameter specifies the control whose node is presently painted. Use the object’s Canvas property representing this parameter value to obtain the canvas used to paint. The Node parameter identifies the node being processed. Use the DisplayRect method of the TTreeNode object representing this parameter value to obtain the bounding rectangle of the node. The State parameter enables you to determine the painted node’s current state. cdsSelected and cdsHot values included into this parameter’s value indicate that the node is selected or hot-tracked respectively. (Note that node hot-tracking is only available when the HotTrack property is set to True).

You can also use the OnAdvancedCustomDrawItem event to perform custom tree node painting. This event should be used in the following instances:

  • You need to perform painting after the default painting has been performed;

  • You want to suppress only painting of node images. The event provides a specially designed parameter for this purpose.

The following sample code provides an example of handling the OnCustomDrawItem event. Opened and closed book images are painted within expanded and collapsed nodes respectively (they are painted in the place of expand buttons and have the same functionality). The caption of the selected node is painted red. Other nodes are painted using black.

procedure TForm1.cxTreeView1CustomDrawItem(Sender: TCustomTreeView;
  Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  ImageRect: TRect;
  RealImageWidth: Integer;
  NodeImage: TBitmap;
begin
  if cdsSelected in State then
    Sender.Canvas.Font.Color := clRed
  else
    Sender.Canvas.Font.Color := clBlack;
  SetBkMode(Sender.Canvas.Handle, TRANSPARENT);
  Sender.Canvas.TextOut(Node.DisplayRect(True).Left, Node.DisplayRect(True).Top, Node.Text);
  if Node.HasChildren then
  begin
    ImageRect := Node.DisplayRect(False);
    ImageRect.Right := Node.DisplayRect(True).Left;
    RealImageWidth := (ImageRect.Right - ImageRect.Left) div (Node.Level + 1);
    ImageRect.Left := ImageRect.Right - RealImageWidth;
    NodeImage := TBitmap.Create;
    if Node.Expanded then
      NodeImage.LoadFromFile('c:\expanded.bmp')
    else
      NodeImage.LoadFromFile('c:\collapsed.bmp');
    Sender.Canvas.Draw(ImageRect.Left, ImageRect.Top, NodeImage);
  end;
  DefaultDraw := False;
end;

The following is the result of code execution.

See Also