Builder C++:带有复选框项目的 TTreeView

Builder C++ : TTreeView with checkbox items

我需要创建一个带有复选框节点的树视图,如下图所示:

怎么做?

谢谢!

TTreeView 组件本身不支持复选框,但标准 Windows TREEVIEW 控件支持,通过 TVS_CHECKBOXES style:

TVS_CHECKBOXES

Version 4.70. Enables check boxes for items in a tree-view control. A check box is displayed only if an image is associated with the item. When set to this style, the control effectively uses DrawFrameControl to create and set a state image list containing two images. State image 1 is the unchecked box and state image 2 is the checked box. Setting the state image to zero removes the check box altogether. For more information, see Working with state image indexes.

Version 5.80. Displays a check box even if no image is associated with the item.

Once a tree-view control is created with this style, the style cannot be removed. Instead, you must destroy the control and create a new one in its place. Destroying the tree-view control does not destroy the check box state image list. You must destroy it explicitly. Get the handle to the state image list by sending the tree-view control a TVM_GETIMAGELIST message. Then destroy the image list with ImageList_Destroy.

If you want to use this style, you must set the TVS_CHECKBOXES style with SetWindowLong after you create the treeview control, and before you populate the tree. Otherwise, the checkboxes might appear unchecked, depending on timing issues.

要将 TVS_CHECKBOXES 样式应用于 TTreeView 组件,您应该派生一个新组件并覆盖虚拟 CreateParams() 方法,例如:

class TMyTreeView : public TTreeView
{
protected:
    virtual void __fastcall CreateParams(TCreateParams &Params);
};

void __fastcall TMyTreeView::CreateParams(TCreateParams &Params)
{
    TTreeView::CreateParams(Params);
    Params.Style |= TVS_CHECKBOXES;
}

要在代码中分配复选框状态,您可以使用 TreeView_GetItem()/TreeView_SetItem() 宏根据需要切换节点的状态图像索引。

或者,更灵活的方法是根据需要简单地将您自己的 TImageList 分配给 TTreeView::StateImages property and fill it with whatever checkbox images you want, and then you can set the TTreeNode::StateIndex 属性。要对用户在复选框上的输入做出反应,请使用 TTreeView::OnClickTTreeView::OnKeyDown 事件相应地切换 TTreeNode::StateIndex

void __fastcall ToggleTreeNodeCheckBox(TTreeNode *Node)
{
    if ((Node) && (Node->StateIndex != -1))
    {
        if (Node->StateIndex == MyCheckedStateImageIndex)
            Node->StateIndex = MyUncheckedStateImageIndex;
        else
            Node->StateIndex = MyCheckedStateImageIndex;
    }
}

void __fastcall TMyForm::TreeView1Click(TObject *Sender)
{
    TPoint P;
    ::GetCursorPos(&P);
    // or: P = Mouse->CursorPos;
    // or: POINTS pts = MAKEPOINTS(::GetMessagePos()); P = Point(pts.x, pts.y);
    P = TreeView1->ScreenToClient(P);
    if (TreeView1->GetHitTestInfoAt(P.x, P.y).Contains(htOnStateIcon))
        ToggleTreeNodeCheckBox(TreeView1->GetNodeAt(P.x, P.y));
}

void __fastcall TMyForm1::TreeView1KeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
    if (Key == VK_SPACE)
        ToggleTreeNodeCheckBox(TreeView1->Selected);
}