Sunday, October 21, 2007

Display Custom TTreeView Item Hints

The TTreeView Delphi control wraps the Windows tree view control. TTreeView is comonly used when a hierarhical structure needs to be displayed to the user. By clicking an item, the user can expand and collapse the associated list of subitems.

In complex tree views, you might want to display customized tooltip (hint) for each tree node.

Delphi's TTreeView exposes two properties you use to set the hint window which appears when the mouse hovers (precisely: when the mouse pointer rests momentarily) over a control: Hint and ShowHint

"Unfortunatelly", the value stored in the Hint property will be displayed, for the tree view, no matter over what item the mouse is.

TreeView Item Related Hint

To display different hints for every node in a tree view, you need to change the Hint property of the TTreeView control depending on the item the mouse is over.

The easiest way to accomplish this, is to handle the OnMouseMove event and set the Hint property (for the tree view) by locating the tree node under the mouse.

The Source

//form's private variable:
lastHintNode : TTreeNode;


//treeView1 OnMouseMove event handler
procedure TForm1.TreeView1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer) ;
  tree: TTreeView;
  hoverNode: TTreeNode;
  hitTest : THitTests;
   //ht : THitTest;
   if (Sender is TTreeView) then
    tree := TTreeView(Sender)

   hoverNode := tree.GetNodeAt(X, Y) ;
   hitTest := tree.GetHitTestInfoAt(X, Y) ;

  //list the hitTest values
   Caption := '';
   for ht in hitTest do
    Caption := Caption + GetEnumName(TypeInfo(THitTest),    integer(ht)) + ', ';

   if (lastHintNode <> hoverNode) then

     if (hitTest <= [htOnItem, htOnIcon, htOnLabel,     htOnStateIcon]) then
       lastHintNode := hoverNode;
       tree.Hint := NodeHint(hoverNode) ;

No comments: