其他分享
首页 > 其他分享> > QTreeWidget

QTreeWidget

作者:互联网

#include <QTreeWidget>

#include <QHeaderView>

{

    // 实例化树结构

    QTreeWidget *pTreeWidget = new QTreeWidget(this);

    // 设置标头

    pTreeWidget->header()->hide();

    pTreeWidget->header()->setResizeMode(QHeaderView::ResizeToContents);

    pTreeWidget->header()->setStretchLastSection(false);

    // 开启滚动条

    pTreeWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    pTreeWidget0>setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    // 去除光标

    pTreeWidget->setFocusPolicy(Qt::NoFocus);

    // 禁止编辑

    pTreeWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

}

1、声明自定义数据类型

Q_DECLARE_METATYPE(CTest*);

EItemType

{

    E_ITEM_ROOT = 0,

    E_ITEM_NODE

}

2、添加自定义类型和数据

CTest *pTest = new CTest(this);

QTreeWidgetItem *pItem =  new QTreeWidgetItem(QStringList(tr("测试")));

pItem->setData(0, Qt::UserRole, E_ITEM_ROOT);

pItem->setData(1, Qt::UserRole, QVariant::fromValue(pTest));

3、获取自定义类型

EItemType type = (EItemType)pItem->data(0, Qt::UserRole).toInt;

4、获取自定义数据

CTest *pTest = pItem->data(1, Qt::UserRole).value<CTest *>();

5、设置节点可编辑重命名

pItem->setFlags(pItem->flags() | Qt::ItemIsEditable);

6、设置节点支持多选

pTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

7、设置节点添加展开按钮

pItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);

标签:pItem,Qt,自定义,pTreeWidget,UserRole,QTreeWidget,CTest
来源: https://blog.csdn.net/lavanana/article/details/94594184