中的拖放操作不复制放置的项目

中的拖放操作不复制放置的项目

本文介绍了QTreeWidget 中的拖放操作不复制放置的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一个父项下的 QTreeWidget-parent 中复制一个项目鼠标操作.为此,我实现了 dropEvent() 并将 dropAction 设置为 Qt.CopyAction.但无论如何,我丢弃的项目并没有被复制到新的父项下.例如.-> 将用户schmidt"拖到LON"组下.

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".

预期行为:我正在删除的项目正在被复制到新的父项下.(例如,用户schmidt"将被添加到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").

完整的工作代码示例:

#!/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_())

推荐答案

移除 dropEvent 方法.

Remove the dropEvent method.

TL;博士;

不需要重写 dropEvent 方法,因为它已经实现了复制项目的所有逻辑.

It is not necessary to override the dropEvent method since it has already implemented all the logic to copy the items.

这篇关于QTreeWidget 中的拖放操作不复制放置的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 01:51