Implementing the wxTreeCtrl

posted on: 2010-04-28 20:22:12



Today we are going to explore the wxWidgets's wxTreeCtrl. This control does pretty much what it says on the tin. It that it displays to the user in a composite pattern (I will be covering design patterns in an upcoming blog). But briefly, this pattern is just a way of representing a relationship where any node can contain child nodes, so on and so forth.

dave nicholas file tree screenshot

The wxTreeCtrl is supported Linux, Windows and Mac. The main benefit of using the wxWidget library is that, wxWidgets are wrappers for native API calls. This means that all forms built using wxWidgets will always use look native using the users colour schemes and appearance settings. So the wxTreeCtrl will always look good.

Anyway the wxTreeCtrl is very easy to use. You firstly need to make sure you have the wxWidgets development libraries and include the following header files.

#include <wx/wx.h>
#include <wx/treectrl.h>

Then we need to declare a wxTreeCtrl variable and assign it and instanciate it.

wxTreeCtrl * m_tree = new wxTreeCtrl(this, wxID_ANY, wxDefaultPosition, wxSize(200,200));

Next we need some elements. We can do this using the following methods that the tree wxTreeCtrl class supports.

wxTreeCtrl

Now we add some items and build program.

wxTreeItemId parentNodeIndex = m_tree->AddRoot(wxT("Root Item"));
parentNodeIndex = m_tree->AppendItem(parentNodeIndex, wxT("node 1"));
m_tree->AppendItem(parentNodeIndex, wxT("Inner node 2"));

The following source code contains a good example of building a wxTreeCtrl from file system directory structure.

source and binary dn_file_tree_example.tar.gz