【问题标题】:С++ Microsoft MFC TreeView IconsС++ Microsoft MFC TreeView 图标
【发布时间】:2019-03-24 08:04:59
【问题描述】:

我通过一篇博客文章编写了 TreeView 控件的代码。我正在尝试将图标添加到列表项。但是没有渲染图标。 我有下一个代码:

void CLeftView::OnInitialUpdate()
{
    CTreeView::OnInitialUpdate();

    // TODO: Add items by GetTreeCtrl().

    HICON hi = NULL;
    hi = AfxGetApp()->LoadIcon(MAKEINTRESOURCE(IDI_ICON1));
    if (hi != NULL)
    {
        MessageBox(NULL, L"resource1");
    }
    else MessageBox(NULL, L"Not resource1");
    HICON lo = NULL;
    lo = AfxGetApp()->LoadIcon(MAKEINTRESOURCE(IDI_ICON2));
    if (lo != NULL)
    {
        MessageBox(NULL, L"resource2");
    }
    else MessageBox(NULL, L"Not resource2");

    CImageList m_tree_imglist;
    CTreeCtrl & tc = CTreeView::GetTreeCtrl();

    m_tree_imglist.Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 2);

    m_tree_imglist.Add(hi);
    m_tree_imglist.Add(lo);


    tc.SetImageList(&m_tree_imglist, TVSIL_NORMAL);

    HTREEITEM hItem;
    hItem = tc.InsertItem(L"Fonts", 0, 0, TVI_ROOT);
    tc.InsertItem(L"Arial", 0, 0, hItem);
    tc.InsertItem(L"Times", 0, 0, hItem);
    tc.Expand(hItem, TVE_EXPAND);
}

图标已添加到资源文件中。我有错误吗?我有带有下一个文本的消息框:“resource1”、“resource2”。

【问题讨论】:

  • 对于一个肮脏而快速的解决方案,请在函数结束之前分离您的局部变量 m_treee_imgList.Detach()。然而,更好的正确解决方案是将变量 m_treee_imgList 声明为 Barmak 所示的类成员。

标签: c++ visual-c++ mfc treeview icons


【解决方案1】:

m_tree_imglist 被声明在栈上,这个图像列表在OnInitialUpdate 退出后被销毁,所以CTreeCtrl 不再有图像列表。

图像列表应该被声明为类成员,这样只要CTreeCtrl 需要它,它就一直有效。注意 m_ 前缀通常在 MFC 中用于表示“类成员”。

class CLeftView : public CTreeView
{
    CImageList m_tree_imglist;
    ...
};

void CLeftView::OnInitialUpdate()
{
    ...
    //CImageList m_tree_imglist; <- remove
    tc.SetImageList(&m_tree_imglist, TVSIL_NORMAL);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多