Delphi custom TTreeNode

Im trying to make my custom TTreeNode Class

for example

TCustomTreeNode = class(TTreeNode)
  private
  public
    Comment:string;
  end;

and i create and add the node in the tree view like this:

var
  NewCustomTreeNode:TCustomTreeNode;
begin
  NewCustomTreeNode:= TCustomTreeNode.Create(TreeView.Items);
  NewCustomTreeNode.Comment:='blqblq';
  TreeView.Items.AddChild(NewCustomTreeNode,'NodeText');

and when i try to access the custom created tree nodes error pops up. For example i do like this:

TCustomTreeNode(TreeNode).Comment:='asdadssadas';

plase help

Answers


The problem with your code is that the call to AddChild results in the tree view creating a new node. And since you didn't tell the tree view to create a node of your sub-class it creates a plain TTreeNode. And then when you try to cast it to a TCustomTreeNode, the world ends.

You need to use the OnCreateNodeClass method to make sure that the tree view is able to create new nodes. Like this:

type
  TCustomTreeNode = class(TTreeNode)
  protected
    procedure Assign(Source: TPersistent); override;
  public
    Comment: string;
  end;

procedure TCustomTreeNode.Assign(Source: TPersistent);
begin
  if Source is TCustomTreeNode then
    Comment := TCustomTreeNode(Source).Comment;
  inherited;
end;


procedure TForm1.FormCreate(Sender: TObject);
var
  NewNode: TCustomTreeNode;
begin
  NewNode := TreeView1.Items.Add(nil, 'Node1') as TCustomTreeNode;
  NewNode.Comment := 'A comment';
  NewNode := TreeView1.Items.Add(nil, 'Node2') as TCustomTreeNode;
  NewNode.Comment := 'Another comment';
end;

procedure TForm1.TreeView1Click(Sender: TObject);
var
  Node: TCustomTreeNode;
begin
  Node := TreeView1.Selected as TCustomTreeNode;
  if Assigned(Node) then
    ShowMessage(Node.Comment);
end;

procedure TForm1.TreeView1CreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass);
begin
  NodeClass := TCustomTreeNode;
end;

I can't claim to being the world's greatest expert on Delphi tree views but in my experience you never create a tree node yourself. You should always call one of the AddXXX methods on TTreeView.Items to create new nodes.


Need Your Help

show spinner before adding widget android

android widget spinner

For a widget I am creating for the Android OS, I want the user to first select a certain option from a Spinner. Just like when you add a shortcut to the homescreen.

Determining "Owner" of Text Edited by Multiple Users

algorithm language-agnostic text diff

You may have noticed that we now show an edit summary on Community Wiki posts: