4

I am using Virtual Tree View. Is there a reliable way to know if a node is root or not?

I try to use

if not Assigned(Node.Parent) then
  Output('This is root')
else
  Output('This is not root')

But does not work.

I try to use

if Node = tvItems.RootNode then
  Output('This is root')
else
  Output('This is not root')

But does not work either.

alancc
  • 487
  • 2
  • 24
  • 68

1 Answers1

3

The ultimate root node in VTV (or VST) is a special invisible node, which acts as parent for all user created root nodes (nodes created with parent = nil). This special invisible node has by design its NextSibling and PrevSibling properties set to point to itself.

To detect whether a node is root node (in the sense of user created root) you can e.g. do:

procedure TForm16.tvItemsNodeClick(Sender: TBaseVirtualTree;
  const HitInfo: THitInfo);
begin
  if HitInfo.HitNode.Parent.NextSibling = HitInfo.HitNode.Parent then
    Caption := 'Root node'
  else
    Caption := 'Not root node';
end;

Alternatively, as OP commented, and without using internal implementation details:

procedure TForm16.tvItemsNodeClick(Sender: TBaseVirtualTree;
  const HitInfo: THitInfo);
begin
  if HitInfo.HitNode.Parent = Sender.RootNode then
    Caption := 'Root node'
  else
    Caption := 'Not root node';
end;

Ref: TBaseVirtualTree.RootNode Property (in Help)

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
  • Thank you very much. I also find another way to check: if HitInfo.HitNode.Parent = tvItems.RootNode then... – alancc Sep 23 '19 at 09:32