0

I need to insert some new nodes to TVirtualStringTree. I use the InsertNode method with a UserData param. But the tree can't show any data. How can I get the userdata on GetText/FreeNode event?

  TMyData = record
    Name: string;
    size: Integer;
  end;
  PMyData = ^TMyData;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
  VirtualStringTree1.NodeDataSize := SizeOf(TMyData);
  Randomize;
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  Data: PMyData;
  Node: PVirtualNode;
begin
  New(Data);
  Data.Name := DateTimeToStr(now);
  Data.size := Random(100);
  Node := VirtualStringTree1.InsertNode(nil, amInsertAfter, Data);
end;

procedure TForm2.VirtualStringTree1FreeNode(Sender: TBaseVirtualTree; Node:
    PVirtualNode);
var
  Data: PMyData;
begin
  Data := Sender.GetNodeData(Node);
  Data.Name := '';
end;

procedure TForm2.VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node:
    PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText:
    WideString);
var
  Data: PMyData;
begin
  Data := Sender.GetNodeData(Node);
  case Column of
    0: CellText := Data.Name;
    1: CellText := IntToStr(Data.size);
  end;
end;
Leo
  • 1,947
  • 2
  • 20
  • 37

1 Answers1

6

When you insert user data in the tree your pointer is stored in the node's internal record. GetNodeData doesn't return the pointer which you passed in, it's the pointer to memory where your pointer is stored. Therefore you need to dereference it:

Data := PMyData(Sender.GetNodeData(Node)^);
Ondrej Kelle
  • 36,941
  • 2
  • 65
  • 128
  • 2
    Actually it depends on what you store in the VT's node. You can store the actual record OR you can store a pointer to your record. Your code is correct if you store the pointer to the record, incorrect if you store the actual record in the node. The code for adding nodes to the tree is not in the user's sample so we have no idea what the user is storing. And that might actually be the question! – Cosmin Prund May 18 '11 at 10:43
  • @Cosmin The code is there, see Button1Click. He's passing pointer to his record as UserData parameter to InsertNode. – Ondrej Kelle May 18 '11 at 10:46
  • I see it now, the OP is storing pointers to heap allocated records. +1. – Cosmin Prund May 18 '11 at 10:48