目录
pyqt 树节点拖拽 改变层级顺序
pyqt 树节点拖拽 QTreeWidget 实例
主界面添加监听
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeWidget, QTreeWidgetItem
from PyQt5.QtCore import Qt, QPoint
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setGeometry(300, 300, 600, 400)
self.setWindowTitle('Tree Widget Drag and Drop Example')
self.treeWidget = QTreeWidget(self)
self.treeWidget.setAcceptDrops(True)
self.treeWidget.setGeometry(10, 10, 580, 380)
self.treeWidget.setHeaderLabels(['Items'])
self.treeWidget.addTopLevelItem(QTreeWidgetItem(["Item 1"]))
self.treeWidget.addTopLevelItem(QTreeWidgetItem(["Item 2"]))
self.treeWidget.setDragEnabled(True)
self.treeWidget.setDropIndicatorShown(True)
self.treeWidget.setDragDropMode(QTreeWidget.InternalMove)
def dragEnterEvent(self, event):
event.accept()
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
event.setDropAction(Qt.MoveAction)
super().dropEvent(event) # Ensure the internal move logic of QTreeWidget is used.
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
自定义treewidget
import sys
from PyQt5 import QtWidgets, QtCore
class CustomTreeWidget(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setHeaderLabels(['Items'])
self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
def dropEvent(self, event):
super().dropEvent(event)
self.print_tree_structure()
def print_tree_structure(self):
def recurse(item, level=0):
print(' ' * level + item.text(0))
for i in range(item.childCount()):
recurse(item.child(i), level + 1)
root = self.invisibleRootItem()
for i in range(root.childCount()):
child = root.child(i)
recurse(child)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('QTreeWidget Drag and Drop Example')
self.setGeometry(300, 300, 400, 300)
# 创建自定义的 QTreeWidget
self.tree = CustomTreeWidget(self)
self.setCentralWidget(self.tree)
# 添加项目
self.add_items()
def add_items(self):
root = QtWidgets.QTreeWidgetItem(self.tree, ['Root'])
child1 = QtWidgets.QTreeWidgetItem(root, ['Child 1'])
child2 = QtWidgets.QTreeWidgetItem(root, ['Child 2'])
grandchild1 = QtWidgets.QTreeWidgetItem(child1, ['Grandchild 1'])
# 展开所有节点
self.tree.expandAll()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())