You can add integrity to a TTreeView by attaching handle objects to the Data property of each TTreeNode (which you can later use to identify the node's purpose). Or, you can maintain a separate data structure that leads you to specific points in the TTreeView.
Let's consider the first option, which is useful for trees with many nodes. (We'll use the baseball tree from the accompanying article.) Assume we have a TTreeNode void* that can point to any object. We create an identifier structure and place one in each TTreeNode we create:
enum entryValue {ev_league = 0, ev_division,
ev_team, ev_player};
struct nodeIdHandle
{
entryValue nodeType;
void* obj;
};
Now, we just insert nodeIdHandles into the TTreeNode Data properties.
Each nodeIdHandle can not only store a pointer to any object (just as
TTreeNode->Data could), but tell you what type it is, as well. (If you're an
advanced C++ programmer, you'll recognize other ways to do this, but our method
will work.) The code in Listing A adds a player node to our TTreeView. We're using the TTreeNode->Data property to store a handle that identifies the player and maintains a pointer to a Stats object.
Listing A: Handle example
nodeIdHandle* anyHandle = new nodeIdHandle; nodeIdHandle* tmpHandle; // Add a new player. newPlayerNode = TreeView1->Items-> AddChild(whereToAdd, "Babe Ruth"); // Set new handle node to player type. Point its object to NULL. anyHandle->nodeType = ev_player; anyHandle->obj = NULL; // Allocate a new Stats object. Stats* playerStats = new Stats(3); // Set the TTreeNode to point to the handle. newPlayerNode->Data = (void*) anyHandle; // Point our handle to Stats. tmpHandle = (nodeIdHandle*) newPlayerNode->Data; tmpHandle->obj = (void*) playerStats;In the second option, we use a separate data structure to manage a TTreeView. It's as simple as creating one or more TTreeNode object pointers to help us locate things quickly in the TTreeView. For example, if we need frequent access to all of the teams in the East division in the American League, we might create a variable that points to the East division TTreeNode:
TTreeNode* alEast;When the tree is built, the node pointer to the East node is stored here:
alEast = TreeView1->Add(americanLeagueNode, "East");