-
设置QTreeWidget的拖拽模式为
InternalMove
-
设置允许拖拽
self.setDragEnabled(True)
class TreeWidget(QTreeWidget):
def __init__(self):
super(TreeWidget, self).__init__()
self.setDragDropMode(QTreeWidget.InternalMove)
self.setDragEnabled(True)
在添加item
时要设置item
的type
属性,同时要设置item
的flags
item1 = QTreeWidgetItem(self, type=Level.LEVEL1)
...
item11 = QTreeWidgetItem(item1, type=Level.LEVEL2)
item11.setFlags(item11.flags() & ~Qt.ItemIsDropEnabled)
- 设置多个flag:
setFlags(item1.flags() | Qt.ItemIsDragEnabled)
- 删除一个flag:
setFlags(item1.flags() & ~Qt.ItemIsDragEnabled)
限制只能拖拽在相同的一级item
中进行拖拽
def dragMoveEvent(self, event):
current_item = self.currentItem()
item = self.itemAt(event.pos())
if item and item.type() == Level.LEVEL2 and current_item.parent() == item.parent():
super(TreeWidget, self).dragMoveEvent(event)
else:
event.ignore()
原理和拖拽移动事件一样
def dropEvent(self,event) -> None:
current_item = self.currentItem()
item = self.itemAt(event.pos())
if item and item.type() == Level.LEVEL2 and current_item.parent() == item.parent():
super(TreeWidget, self).dropEvent(event)
else:
event.ignore()
源码下载:戳这里
方法分如下两步:第一步,在datatree类(继承自qtreewidget)的构造函数中设置这棵树具有如下两种特征:第二步,重写 startdrag()函数,在里面写上如下代码://
刚进公司没多久,老大就让做一个实现拖放的小插件,要求可拖拽,可缩放。从网上查了很多资料,也看了别人写的demo,总算摸索出一些门道,下面分享给大家,如有疑问,可评论,大家一起学习!
QCTreeWidget.cpp
// 左侧项目树
QCTreeWidget::QCTreeWidget(const QString& text, QWidget *parent)
: ...
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QColor, QBrush, QDrag, QFont
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu
from PyQt5.QtCore import Qt, QMimeData, QVariant, QPoint