问题
I want to copy an item from a QTreeWidget
-parent under another parent via a drag & drop mouse operation.
For this, I have implemented the dropEvent()
and am setting the dropAction
to Qt.CopyAction
.
But anyway, the item I am dropping is not being copied under the new parent.
E.g. -> dragging the user "schmidt" under the group "LON".
Expected behaviour: the item I am dropping is being copied under the new parent. (e.g. user "schmidt" will be added under group "LON").
Full working code example:
#!/usr/bin/env python3
# coding = utf-8
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MyTreeWidget(QtWidgets.QTreeWidget):
def __init__(self):
QtWidgets.QTreeView.__init__(self)
self.setSelectionMode(self.SingleSelection)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
def dropEvent(self, event):
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.tree = MyTreeWidget()
self.tree.setRootIsDecorated(True)
self.tree.setHeaderHidden(True)
self.setCentralWidget(self.tree)
itemUsers = QtWidgets.QTreeWidgetItem(self.tree, ["User"])
itemUsers.addChild(QtWidgets.QTreeWidgetItem(itemUsers, ["schmidt"]))
itemUsers.addChild(QtWidgets.QTreeWidgetItem(itemUsers, ["weber"]))
itemMdt = QtWidgets.QTreeWidgetItem(self.tree, ["Group"])
itemMdt.addChild(QtWidgets.QTreeWidgetItem(itemMdt, ["FFM"]))
itemMdt.addChild(QtWidgets.QTreeWidgetItem(itemMdt, ["LON"]))
itemMdt.addChild(QtWidgets.QTreeWidgetItem(itemMdt, ["NY"]))
self.show()
self.setGeometry(400, 400, 400, 400)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui = MyMainWindow()
sys.exit(app.exec_())
回答1:
Remove the dropEvent method.
TL; DR;
It is not necessary to override the dropEvent method since it has already implemented all the logic to copy the items.
来源:https://stackoverflow.com/questions/58919468/drag-drop-operation-in-qtreewidget-not-copying-the-dropped-item