TTreeView: how to check/uncheck ONLY children from a TTreeNode?

124 views Asked by At

Windows 10, Delphi 11.

I want to set .Checked only for children of a single TTreeNode with checkboxes. This is the default behavior in TreeViews. But the following code also selects all siblings (on the same level as the starting node). In fact, the call Node.GetNextChild() and Node.GetNextSibling() don't seem to make any difference.

procedure TMapIntForm.CheckAllNodes(Node: TTreeNode; Check: Boolean);
var
  AParent: TTreeNode;
begin
  AParent := Node;
  while (Node <> nil) do
  begin
    Node.Checked := Check;
    CheckAllNodes(Node.GetFirstChild(), Check);
    if Node <> TreeView.Selected then
      Node := Node.GetNextChild(Node) // .GetNextSibling()?
    else Node := nil;
  end;
end;

How do I check only children from a node on a certain level without other nodes on the same level?

1

There are 1 answers

0
Remy Lebeau On BEST ANSWER

You are passing the wrong node into GetNextChild(). It expects a child node of a parent node on which it is called, but you are passing it the parent node itself instead.

I would suggest using a different loop to iterate the child nodes:

procedure TMapIntForm.CheckAllNodes(Node: TTreeNode; Check: boolean);
var
  AChild: TTreeNode;
begin
  Node.Checked := Check;
  AChild := Node.getFirstChild;
  while (AChild <> nil) do
  begin
    CheckAllNodes(AChild, Check);
    if AChild.Selected then Break;
    AChild := AChild.getNextSibling;
  end;
end;