how to add objects to virtualtreeview

柔情痞子 提交于 2019-12-08 13:20:40

问题


In short, I'm trying to add Object into VirtualTreeView but am always getting error EAccessViolation at CellText I'm wondering about the reason for the error i tried to do my best but without result...

this is my attempt:

 TForm1 = class(TForm)
 private

 public

 end;

 TPerson = class;

 PPersonNode = ^TPersonNode;
 TPersonNode = record
   PersonObj: TPerson;
 end;

 TPerson = class(TObject)
 private
   FName: string;
 public
   property Name: string read FName write FName;
 end;

 procedure TForm1.Button1Click(Sender: TObject);  
 var
   PersonRec: PPersonNode;
 begin
   PersonRec := VirtualStringTree1.GetNodeData(VirtualStringTree1.AddChild(nil));
   PersonRec.PersonObj := TPerson.Create;
   PersonRec.PersonObj.Name := 'aaa'; 
 end;

 procedure TForm1.VirtualStringTree1GetNodeDataSize(Sender: TBaseVirtualTree;
   var NodeDataSize: Integer);
 begin
   NodeDataSize := SizeOf(TPersonNode);
end;

procedure TForm1.VirtualStringTree1GetText(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
   PersonRec: PPersonNode;
begin
   PersonRec := Sender.GetNodeData(Node);
   CellText := PersonRec.PersonObj.Name;
end;

回答1:


It looks like the OnGetText event is being fired before the TPerson object has been created. Try checking that the object isn't nil first:

procedure TForm1.VirtualStringTree1GetText(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
   PersonRec: PPersonNode;
begin
   PersonRec := Sender.GetNodeData(Node);

   if PersonRec <> nil then  // <- check that the object has been created
     CellText := PersonRec.PersonObj.Name;
end;



回答2:


I would change this:

procedure TForm1.Button1Click(Sender: TObject);  
var
 PersonRec: PPersonNode;
begin
 PersonRec := VirtualStringTree1.GetNodeData(VirtualStringTree1.AddChild(VirtualStringTree1.RootNode));
 PersonRec.PersonObj := TPerson.Create;
 PersonRec.PersonObj.Name := 'aaa'; 
end;

and this:

procedure TForm1.VirtualStringTree1GetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
 PersonRec: PPersonNode;
begin
 if Assigned(Node) then
 begin
  PersonRec := Sender.GetNodeData(Node);
  CellText := PersonRec.PersonObj.Name;
 end;
end;


来源:https://stackoverflow.com/questions/14136951/how-to-add-objects-to-virtualtreeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!