头文件 #ifndef _MYTREECTRL_ #define _MYTREECTRL_ #include "wx/wx.h" #include "wx/imaglist.h" #include "wx/treectrl.h" class MyTreeCtrl: public wxTreeCtrl { public: MyTreeCtrl() : wxTreeCtrl(), m_imageList(16, 16, TRUE) {} MyTreeCtrl(wxWindow *parent, wxWindowID id = -1, const wxPoint& pt = wxDefaultPosition, const wxSize& sz = wxDefaultSize, long style = wxTR_HAS_BUTTONS, const wxValidator& validator = wxDefaultValidator, const wxString& name = _T("treectrl")) : wxTreeCtrl(), m_imageList(16, 16, TRUE) { Create(parent, id, pt, sz, style, validator, name); } bool Create(wxWindow *parent, wxWindowID id = -1, const wxPoint& pt = wxDefaultPosition, const wxSize& sz = wxDefaultSize, long style = wxTR_HAS_BUTTONS, const wxValidator& validator = wxDefaultValidator, const wxString& name = _T("treectrl")); virtual ~MyTreeCtrl() {} void OnLeftDown(wxMouseEvent& event); void SetChildImage(wxTreeItemId parentId, int imageIndex, wxTreeItemIdValue cookie); private: wxImageList m_imageList; DECLARE_CLASS(MyTreeCtrl) DECLARE_EVENT_TABLE() }; #endif 源文件 #include "MyTreeCtrl.h" #include "CheckUser.h" #include "checked.xpm" #include "unchecked.xpm" #include "checked_dis.xpm" #include "unchecked_dis.xpm" IMPLEMENT_CLASS(MyTreeCtrl, wxTreeCtrl) BEGIN_EVENT_TABLE(MyTreeCtrl, wxTreeCtrl) EVT_LEFT_DOWN(MyTreeCtrl::OnLeftDown) END_EVENT_TABLE() bool MyTreeCtrl::Create(wxWindow* parent, wxWindowID id, const wxPoint& pt, const wxSize& sz, long style, const wxValidator& validator, const wxString& name) { if (!wxTreeCtrl::Create(parent, id, pt, sz, style, validator, name)) return FALSE; SetImageList(&m_imageList); // the add order must respect the wxCLC_XXX_IMGIDX defines in the headers ! m_imageList.Add(wxIcon(unchecked_xpm)); m_imageList.Add(wxIcon(checked_xpm)); m_imageList.Add(wxIcon(unchecked_dis_xpm)); m_imageList.Add(wxIcon(checked_dis_xpm)); return TRUE; } void MyTreeCtrl::SetChildImage(wxTreeItemId parentId, int imageIndex, wxTreeItemIdValue cookie) { if (ItemHasChildren(parentId)) { wxTreeItemId childId = GetFirstChild(parentId, cookie); while (childId.IsOk()) { SetItemImage(childId, imageIndex); SetChildImage(childId, imageIndex, cookie); childId = GetNextChild(parentId, cookie); } } } void MyTreeCtrl::OnLeftDown(wxMouseEvent& event) { if (!event.LeftDown()) { event.Skip(); return; } wxPoint pt = event.GetPosition(); int flag = 0; wxTreeItemId hitId = HitTest(pt, flag); //Toggle(hitId); int imageIndex = GetItemImage(hitId); if (flag & wxTREE_HITTEST_ONITEMICON) { wxTreeItemIdValue cookie = 0; switch (imageIndex) { case 0: SetItemImage(hitId, 1); SetChildImage(hitId, 1, cookie); break; case 1: SetItemImage(hitId, 0); SetChildImage(hitId, 0, cookie); break; } } event.Skip(); } 几个xpm文件不方便上传,也可以直接使用wxIcon