delphipointersvirtualtreeviewtvirtualstringtree

Writing data to PVirtualNode without setting each field value manually


Lets say I have this node data record:

Type
  PPerson = ^TPerson;
  TPerson = record
   Name: String;
   Age: Integer;
   SomeBool: Boolean;
  end;

To populate my VirtualStringTree, I would do this:

Procedure AddToTree(Person: TPerson);
Var
 Node: PVirtualNode;
 Data: PPerson;
Begin
 Node := VT.AddChild(nil);
 Data := VT.GetNodeData(Node);
 Data.Name := Person.Name;
 Data.Age  := Person.Age;
 Data.SomeBool := Person.SomeBool;
End;

Procedure TMyForm.MyButtonClick(Sender: TObject);
Var
 Person: TPerson;
Begin
 Person.Name := 'Jeff';
 Person.Age := 16;
 Person.SomeBool := False;
 AddToTree(Person);

End:

Now, while this works perfectly fine, I would like to simplify it, so whenever I add new fields to the record, I wont have modify the AddToTree method.

So I tried this:

Procedure AddToTree(Person: TPerson);
Begin
 VT.AddChild(nil,@Person);
End;

This compiles, but it appears the PVirtualNode did not get the data, because my VT is not displaying anything, and when breaking in the OnGetText event, I see the variables are empty.

What am I doing wrong? :)


Solution

  • Records support the assignment operator:

    procedure AddToTree(const Person: TPerson);
    var
      Node: PVirtualNode;
      Data: PPerson;
    begin
      Node := VT.AddChild(nil);
      Data := VT.GetNodeData(Node);
      Data^ := Person;
    end;