Introduction
Recently, I needed to use in an application a data structure that is very similar to CTreeCtrl
. But, as CTreeCtrl
is a CWnd
object, I cannot use this one, because I didn't want to have a CWnd
object. And because I didn't find something that fit my needs, I have built one myself. And I decided to share it here ...
Structure
This objects are derived from CObject
, but this was not necessary (only because you might need to implement the serialization inside). There are implemented almost any methods that are needed to use this object like a CTreeCtrl
object:
typedef struct CTreeItem* HTREEOBJECTITEM;
class CTreeObject : virtual public CObject
{
.....
public:
CTreeObject();
virtual ~CTreeObject();
HTREEOBJECTITEM InsertItem(CString sText, HTREEOBJECTITEM hParent = NULL);
void SetItemData(HTREEOBJECTITEM hItem, DWORD dwItemData);
DWORD GetItemData(HTREEOBJECTITEM hItem);
void DeleteItem(HTREEOBJECTITEM hItem);
void DeleteAllItems();
POSITION GetRootHeadPosition() {return m_PtrItem.GetHeadPosition();}
POSITION GetRootTailPosition() {return m_PtrItem.GetTailPosition();}
HTREEOBJECTITEM GetNextSiblingItem(POSITION& pos, HTREEOBJECTITEM hParentItem = NULL);
HTREEOBJECTITEM GetPrevSiblingItem(POSITION& pos, HTREEOBJECTITEM hParentItem = NULL);
POSITION GetChildItem(HTREEOBJECTITEM hItem);
HTREEOBJECTITEM GetParentItem(HTREEOBJECTITEM hItem);
CString GetItemText(HTREEOBJECTITEM hItem) const;
int GetChildCount(HTREEOBJECTITEM hItem) const;
int GetRootCount() const {return m_PtrItem.GetCount();}
BOOL IsValidItem(HTREEOBJECTITEM hItem) const;
};
Using the Code
Using this object is very simple, and similar to the model, CTreeCtrl
:
HTREEOBJECTITEM hRoot0 = m_Tree.InsertItem(_T("hRoot0"));
HTREEOBJECTITEM hhParent0 = m_Tree.InsertItem(_T("hParent0"), hRoot0);
m_Tree.InsertItem(_T("hItem0"), hhParent0);
m_Tree.InsertItem(_T("hItem1"), hhParent0);
And listing them:
POSITION pos = m_Tree.GetRootHeadPosition();
while(NULL != pos)
{
HTREEOBJECTITEM hRoot = m_Tree.GetNextSiblingItem(pos);
POSITION posParent = m_Tree.GetChildItem(hRoot);
while(NULL != posParent)
{
HTREEOBJECTITEM hParent = m_Tree.GetNextSiblingItem(posParent, hRoot);
TRACE(_T("Item %s\n"), m_Tree.GetItemText(hParent));
}
}
To check an item if it exists or is valid, I have IsValidItem(HTREEOBJECTITEM hItem)
method.
I attach with this article a sample project that illustrates how to use this class ...
So, anywhere you need to have a tree data structure (XML, DICOM structure, data groups, etc.) you can freely use this object ... enjoy it !
Future Development
The next step in developing this class is to add serialization, and to templatize it.
History
- 2017-10-08 - Initial release