您的位置:首页 > 其它

MFC Tree Control的使用

2011-07-28 22:46 1411 查看
1.InsertItem 添加节点
参数: 文字,图标,父节点
返回: HTREEITEM
示例: 添加一系列节点
HTREEITEM hItem = m_Tree.InsertItem("root",NULL,NULL);///root就是节点的标题
int i,j;
for (i=0;i<4;i++) {
HTREEITEM hSubItem = m_Tree.InsertItem("item",NULL,NULL,hItem);
for (j=0;j<3;j++) {
m_Tree.InsertItem("subitem",NULL,NULL,hSubItem);
}
}

InsertItem函数的第一个参数就是设置他的节点标题
2.ModifyStyle 设置风格
参数: 取消的风格,增加的风格
示例: 在对话框初始化时设置风格
BOOL CMfc1Dlg::OnInitDialog(){
//...
m_Tree.ModifyStyle(NULL,TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT);
}

3.DeleteItem 删除节点

4.DeleteAllItems 删除全部节点

5.Expand 展开/收缩节点
参数: 节点HTREEITEM,展开/收缩
示例:
m_Tree.Expand(hItem,TVE_EXPAND);详细:
MFC Tree controls are one of the useful controls to show a hierarchical view of items. They can show the folders list, any parent - child relationship items etc.,
CTreeCtrl is the class which handles all the MFC Tree Control related operations
. It has all the necessary methods to Add MFC Tree control items, Retrieve selected items, Remove the items and other event handlers needed.
This article explains how to Initialize a MFC Tree control, Add items to Tree control, Retrieve items, Delete items and one event, Selection Change.

MFC Tree Control - CTreeCtrl Initialization:
These are the necessary steps to initialize a Tree Control in MFC.
Add a Tree control Resource to the dialog box in the Resource
Assign a Resource ID to the tree control using the properties dialog.
Add a CTreeCtrl type member variable to the Tree Control using Class Wizard. (To do this, press Ctrl + W keys together to invoke the class wizard. In Member Variables Tab, select the tree control's ID and press Add member. Variables can be created now). Let us assume the variable name to be m_MFC_Tree
MFC Tree Control - Adding Items:
For adding items in Tree control, the function InsertItem is the one to be used. This returns a handle to the tree item type as HTREEITEM. Look at the following samples.
Adding item to the root:
HTREEITEM hParent = m_MFC_Tree.InsertItem("ItemText",TVI_ROOT);
The InsertItem function returns a handle to HTREEITEM, which can be used for adding items down the levels. This function InsertItem is overloaded and has some more signatures. But for a simple insert of items, this function signature is more than enough for us.
Adding child items to the Parent:
This is a very simple operation. We need the parent handle of type HTREEITEM for creating the child item.
HTREEITEM hParent = m_MFC_Tree.InsertItem("ItemText",TVI_ROOT);
HTREEITEM hChild = m_MFC_Tree.InsertItem("Child ItemText",hParent,TVI_LAST);
Usually adding child items in such Tree controls will use recursive functions. For example if the requirement is to list all the folders under C:\ drive, it has to go through each folder to find the sub-folders. Recursive functions will handle such requests easily. A good example will be Windows Explorer
.
If there are no "+" or "lines" found in the tree, change the Has Buttons and Has Lines properties of the Tree Control resource using the properties dialog box.
MFC Tree Control - Retrieving Selected Items:
There are two steps to this operation. We need to find the handle for the selected item and then retrieve the text for the corresponding item.
HTREEITEM hItem = m_MFC_Tree.GetSelectedItem();
CString strItemText = m_MFC_Tree.GetItemText(hItem);

MFC Tree Control - Deleting Selected Items:
This is also very similar to the select operation. First we find the handle of the selected item to be deleted and then delete the item.
HTREEITEM hItem = m_MFC_Tree.GetSelectedItem();
m_MFC_Tree.DeleteItem(hItem);
MFC Tree Control Event - Selection Changed:
To Add a handler for Selection Change:
Open the class wizard
Go to the Message maps tab
Select the Tree control on the left side object IDs list box and select TVN_SELCHANGED on the right Messages List box.
Click Add function and go to the function.
The following sample shows a Message box whenever there occurs a selection change event in the Tree control.
void CCoderSourceDlg::OnSelchangedTreectrl(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
// TODO: Add your control notification handler code here
HTREEITEM hItem = m_MFC_Tree.GetSelectedItem();
CString strItemText = m_MFC_Tree.GetItemText(hItem);
MessageBox(strItemText);
*pResult = 0;
}
Though this article does not cover every thing on the tree control, this should be enough to do some basic level of programming
with MFC Tree control.
原文链接: http://www.functionx.com/visualc/controls/treectrl.htm
MFC Controls: The Tree
Control

Overview

A tree control is an object that displays a hierarchical list of items arranged as a physical tree but a little upside down. The items display in a parent-child format to show those that belong to interrelated categories, such as parent to child and child to grandchild, etc; or folder to subfolder to file. Here is an example of a tree list:

The starting item of the tree is sometimes called the root and represents the beginning of the tree. While most tree list have one root, it is not unusual to have a tree list that has many roots, as long as the tree creator judges it necessary. Here is an example:

Each item, including the root, that belongs to the tree is referred to as a node. An item that belongs to, or depends on, another can also be called a leaf. Creation of a Tree Control

The concept of a tree list is implemented in the MFC library by the CTreeCtrl class. To create a tree list on a dialog box or a form, at design time, on the Controls toolbox, click the Tree Control button and click the desired area on a dialog box or a form:

Alternatively, to programmatically create a tree list, declare a variable or a pointer to CTreeCtrl. To initialize the control, call its Create() method. Here is an example:
private: CTreeCtrl *TreeSoft;};-----------------------------------------------------
// Tree1Dlg.cpp : implementation file//CTree1Dlg::CTree1Dlg(CWnd* pParent /*=NULL*/) : CDialog(CTree1Dlg::IDD, pParent){ //{{AFX_DATA_INIT(CTree1Dlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); TreeSoft = new CTreeCtrl;}CTree1Dlg::~CTree1Dlg(){ delete TreeSoft;}BOOL CTree1Dlg::OnInitDialog(){ CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221); return TRUE; // return TRUE unless you set the focus to a control}

Tree List Properties

As mentioned already, a tree list is meant to display items in a list driven by a root and followed by one or more leaves. The items are mainly made of text. Optionally, to display a check box on the left side of the text, set the Check Boxes property to True or add the TVS_CHECKBOXES style (if you are using MSVC 6 and you had added the Tree Control button to the form or dialog box, open the resource file as text and manually add this style because it may not be available on the Properties window).
To guide the user with the tree items, the control uses tool tips. If you will need access to the information stored in tool tips, set the Info Tip property to True or add the TVS_INFOTIP style. If you do not want to display tool tips, set the Tool Tips property to False or create it with the TVS_NOTOOLTIPS style.

When a node has children or leaves, to show this, you may want to display lines connecting these relationships. To do this at design time, set the Has Lines property to True.
If you are programmatically creating the control and you want to display lines among related nodes, add the TVS_HASLINES style.

A node that has dependent children can display or hides them. To display its leaves, a node must be expanded. To hide its leaves, a node must collapse. These operations must be obvious to the user but something should indicate whether a node has dependent or not. This can be illustrated by a button that accompany such a node. To add these buttons to the control, at design time, set the Has Buttons property to True. This is equivalent to dynamically creating a tree list with the TVS_HASBUTTONS style
Unless you have a reason to do otherwise, it is usually a good idea to combine both the Has Buttons (or TVS_HASBUTTONS) and the Has Lines (or TVS_HASLINES) styles:
To show which item is the root, or which items play the roles of roots, of the tree list, you can display a line from the root(s) to the child(ren). To do this, at design time, set the Lines At Root property to True or add the TVS_LINESATROOT style. The line from the root(s) to to the child(ren) can display only if the control has the Has Lines property set to True or the TVS_HASLINES style.

When using the list, the user typically selects an item by clicking it. If you want the mouse cursor to turn into a pointer finger and to underline the item when the mouse is over the node, set the Track Select property to True or create the control with the TVS_TRACKSELECT style.
Once the mouse pointer is on top of the desired item, the user can click to select it.

When the user clicks another control or another application
, the node that was selected would lose its selection as the tree control would have lost focus. If you want the tree to always show the selected item even if the control loses focus, set its Show Selection Always property to True or create the control with the TVS_SHOWSELALWAYS style.
Besides selecting an item, when a node has children, to expand it, the user can double-click the node or click its button if available. Simply selecting the node does not expand it. If you want the selected node to automatically expand without the user having to double-click or click its button, set its Single Expand property to True or create it with the TVS_SINGLEEXPAND style.
When the items of a tree control display or when the nodes expand, they may span beyond the allocated rectangle of the control. When this happens, a vertical and/or a horizontal scroll bars may automatically display. This is because, by default, the Scroll property is set to True. If you do not want any scroll bar, set the Scroll property to False or create the control with the TVS_NOSCROLL style.
Another operation the user can perform on a node consists of changing its text. If you want to allow this, set the control’s Edit Labels to True or add the TVS_EDITLABELS style to it.
A user can be allowed to add items to the list by drag-n-drop operations. If you want to prevent this, set the Disable Drag Drop property to True or create the control with the TVS_DISABLEDRAGDROP style.

Tree Controls Methods

After adding or creating a tree control, you may want to fill it with the necessary items. Each node of the control is an HTREEITEM object. To create a new node, call the CTreeCtrl::InsertItem() method. It comes in various versions. One of them is:
HTREEITEM InsertItem(LPCTSTR lpszItem, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST );The easiest way to add an item consists of calling the InsertItem() method with a null-terminated string as argument because this is the only required argument of this version. Here is an example:
BOOL CTree1Dlg::OnInitDialog(){ CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221); TreeSoft->InsertItem("Office Production"); return TRUE; // return TRUE unless you set the focus to a control}In this case, the item would appear as the root. You can add as many nodes like that and each would appear as a root:
BOOL CTree1Dlg::OnInitDialog(){ CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221); TreeSoft->InsertItem("Office Production"); TreeSoft->InsertItem("Company Management"); TreeSoft->InsertItem("Software Development"); TreeSoft->InsertItem("Human Interaction"); return TRUE; // return TRUE unless you set the focus to a control}
When calling this version of the InsertItem() method, if you do not pass the second argument, the node is created as root. This is because the root item has an HTREEITEM value of TVI_ROOT, which is passed as default. You can also pass the second argument as NULL, which would produce the same effect.
The InsertItem() method returns an HTREEITEM value. You can use this value as a parent to a leaf item. This is done by passing it as the second argument when creating a leaf. Here is an example:
BOOL CTree1Dlg::OnInitDialog(){ CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_SINGLEEXPAND | TVS_SHOWSELALWAYS | TVS_TRACKSELECT, CRect(10, 10, 200, 240), this, 0x1221); HTREEITEM hTree, hCompany; hTree = TreeSoft->InsertItem("Software Production", TVI_ROOT); hCompany = TreeSoft->InsertItem("Microsoft", hTree); TreeSoft->InsertItem("Office", hCompany); TreeSoft->InsertItem("Visual Studio", hCompany); TreeSoft->InsertItem("Servers", hCompany); hCompany = TreeSoft->InsertItem("Jasc", hTree); TreeSoft->InsertItem("Paint Shop Pro", hCompany); TreeSoft->InsertItem("Animation Shop", hCompany); hCompany = TreeSoft->InsertItem("Lotus", hTree); TreeSoft->InsertItem("Notes", hCompany); TreeSoft->InsertItem("Smart Office", hCompany); hCompany = TreeSoft->InsertItem("Macromedia", hTree); TreeSoft->InsertItem("Flash", hCompany); return TRUE; // return TRUE unless you set the focus to a control}
When using the InsertItem() method as we have done so far, the items are added in the order of their appearance. Besides creating new nodes, the InsertItem() method also allows you to control the order in which to insert the new item. The new leaf can be added as the first or the last child of a node. To do this, pass a third argument to this version of the InsertItem() method and give it the TVI_FIRST to be the first child or TVI_LAST to be the last child of the current parent node. Here is an example:
BOOL CTree1Dlg::OnInitDialog(){ CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_SINGLEEXPAND | TVS_SHOWSELALWAYS | TVS_TRACKSELECT, CRect(10, 10, 200, 240), this, 0x1221); HTREEITEM hTree, hCompany; hTree = TreeSoft->InsertItem("Software Production", TVI_ROOT); hCompany = TreeSoft->InsertItem("Microsoft", hTree); TreeSoft->InsertItem("Office", hCompany); TreeSoft->InsertItem("Graphics Manipulation", hCompany, TVI_LAST); TreeSoft->InsertItem("Project Management", hCompany); TreeSoft->InsertItem("Software Develoment", hCompany); TreeSoft->InsertItem("Operating Systems", hCompany, TVI_FIRST); TreeSoft->InsertItem("Software Documentation", hCompany); hCompany = TreeSoft->InsertItem("Jasc", hTree); TreeSoft->InsertItem("Paint Shop Pro", hCompany); TreeSoft->InsertItem("Animation Shop", hCompany); hCompany = TreeSoft->InsertItem("Lotus", hTree); TreeSoft->InsertItem("Notes", hCompany); TreeSoft->InsertItem("Smart Office", hCompany); hCompany = TreeSoft->InsertItem("Macromedia", hTree); TreeSoft->InsertItem("Flash", hCompany); return TRUE; // return TRUE unless you set the focus to a control}
Tree Control Messages

Most messages of the tree controls are notification messages that are sent to its parent window. For example, the NM_CLICK message is sent to the dialog box or the form, that acts as the parent, that the tree control has been clicked. If the click was done with the right mouse button, the NM_RCLICK message is sent instead. In the same way, if the user double-clicks the control an NM_DBLCLK message is sent. If the user double-clicked with the right mouse button, the NM_CDBLCLK message is sent.
As mentioned already, the user has the ability to expand a node that has at least one child. When the user initiates an action that would expand a node, the tree control sends a TVN_ITEMEXPANDING. After the item has expanded, the control sends the TVN_ITEMEXPANDED message.

Tree Control With Bitmaps or Icons
Bitmaps can be used to enhanced the display of items on a tree control. Each tree item can be configured to display or not to display a small picture on its left. To do this, you can declare a CImageList variable and add pictures to it. Once the image list is ready, you can call the CTreeCtrl::SetImageList() method. Its syntax is:
CImageList* SetImageList(CImageList * pImageList, int nImageListType);The first argument, pImageList, is a pointer to a CImageList variable. The nImageListType argument specifies the type of image list that will be used. The possible values are:
Value Type Description
LVSIL_NORMAL The image list is made of large icons
LVSIL_SMALL The image list is made of small icons
LVSIL_STATE The image list is made of state images

To specify the pictures used for a tree item, call one of the following versions of the CTreeCtrl:: InsertItem() methods:
HTREEITEM InsertItem(UINT nMask, LPCTSTR lpszItem, int nImage, int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam, HTREEITEM hParent, HTREEITEM hInsertAfter );HTREEITEM InsertItem(LPCTSTR lpszItem, int nImage, int nSelectedImage, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST);The nMask argument specifies the type of value used to set on the list item. As seen already, the lpszItem is the text that will be displayed for the current item.
The value of nImage is the index of the image used for the item being inserted from the image list. The nSelectedImage value is the index of the image that will display when the inserted item is selected or has focus.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: