QTreeWidget拖拽节点

编程

一、前言

  在使用QTreeWidget创建树状栏时,期望可以通过拖动节点移动到不同的组,但是组禁止拖动;节点只分为组(父节点)和子项,子项a拖动到另一个组X的子项b时,a作为X的子项,而非b的子项;

二、实现过程

  1、定义item的属性,设置到data中,对项的类别作判断

1 typedef enum

2{

3 ITEM_MIN,

4 ITEM_PARENT,

5 ITEM_SUB,

6 ITEM_MAX

7 }TREE_ITEM_ENUM;

项类别定义

  2、继承拖拽事件

1protected:

2//虚函数重载

3virtualvoid contextMenuEvent(QContextMenuEvent *event);

4virtualvoid startDrag(Qt::DropActions supportedActions);

5virtualvoid dropEvent(QDropEvent *event);

6virtualvoid dragEnterEvent(QDragEnterEvent *event);

继承拖拽事件

  3、构造时开启拖拽响应属性

1 setSelectionMode(QAbstractItemView::SingleSelection); //单选

2 setDragEnabled(true); //启用拖放

3 setAcceptDrops(true); //设置拖放

4 setDropIndicatorShown(true); //设置显示将要被放置的位置

5 setDragDropMode(QAbstractItemView::InternalMove); //设置拖放模式为移动项目,否则为复制项目

6 setIndentation(20);

7//setRootIsDecorated(false);

8this->header()->hide();//隐藏头

拖拽响应

  4、执行拖拽,子项a拖动到子项b时,先找到b的父类,删除a再新建个a(复制数据),设置父类为b的父类

 1void TreeWidget::dropEvent(QDropEvent *event)

2{

3if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))

4 {

5 QByteArray itemData = event->mimeData()->data("application/x-qabstractitemmodeldatalist");

6 QTreeWidgetItem *srcItem = (QTreeWidgetItem*)((void*)QVariant(itemData).toInt());

7 QTreeWidgetItem *desItem = itemAt(event->pos());

8

9if (desItem == srcItem || desItem == NULL)

10 {

11event->ignore();

12return;

13 }

14

15 TREE_ITEM_ENUM srcType = (TREE_ITEM_ENUM)srcItem->data(0, Qt::UserRole).toInt();

16 TREE_ITEM_ENUM desType = (TREE_ITEM_ENUM)desItem->data(0, Qt::UserRole).toInt();

17

18if (srcType == ITEM_SUB)

19 {

20if(ITEM_PARENT == desType)

21 QTreeWidget::dropEvent(event);

22else

23 {

24 QTreeWidgetItem *parentItem = desItem->parent();

25int index = parentItem->indexOfChild(desItem);

26 QTreeWidgetItem *item = new QTreeWidgetItem();

27 item->setData(0, Qt::UserRole, srcItem->data(0, Qt::UserRole));

28 item->setText(0, srcItem->text(0));

29 parentItem->insertChild(index, item);

30

31delete srcItem;

32 srcItem = NULL;

33 }

34 }

35 }

36 }

执行拖拽事件

  5、禁用拖拽组

 1void TreeWidget::dragEnterEvent(QDragEnterEvent *event)

2{

3if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))

4 {

5 QByteArray itemData = event->mimeData()->data("application/x-qabstractitemmodeldatalist");

6 QTreeWidgetItem *srcItem = (QTreeWidgetItem*)((void*)QVariant(itemData).toInt());

7int type = srcItem->data(0, Qt::UserRole).toInt();

8if(ITEM_PARENT == type)

9event->ignore();

10else

11event->accept();

12 }

13else

14event->ignore();

15 }

禁用拖拽组

  6、运行效果如下

  

posted @

2021-07-08 20:10 

凉天满月 

阅读(6

评论(0

编辑 

收藏 

举报

刷新评论刷新页面返回顶部

Copyright © 2021 凉天满月


Powered by .NET 5.0 on Kubernetes

以上是 QTreeWidget拖拽节点 的全部内容, 来源链接: utcz.com/z/519765.html

回到顶部