简而言之,我正在尝试将Object添加到VirtualTreeView中,但我总是在CellText上收到错误EAccessViolation
我想知道错误的原因我试图尽我所能但没有结果... < / p>
这是我的尝试:
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;
答案 0 :(得分:2)
在创建TPerson对象之前,似乎触发了 OnGetText 事件。尝试先检查对象是否为零:
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;
答案 1 :(得分:0)
我会改变这个:
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;
和此:
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;