【问题标题】:Drag Drop Operation in QTreeWidget not copying the dropped itemQTreeWidget中的拖放操作不复制拖放的项目
【发布时间】:2019-11-18 16:55:10
【问题描述】:

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

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

【问题讨论】:

    标签: python pyqt drag-and-drop pyqt5 qtreewidget


    【解决方案1】:

    删除 dropEvent 方法。

    TL;博士;

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

    【讨论】:

    • 谢谢。如果是这种情况,我将如何验证该项目已存在于新父项下,然后跳过它?
    • @ProfP30 可以覆盖 dropEvent 方法,如果有效则调用 super():def dropEvent(self, event): if validation_function(event): super().dropEvent(event)
    • 谢谢!我如何评估删除的数据(例如删除的 QTreeWidgetItem 的文本。源参数仅包含 QTreeWidgets 名称。我如何遍历所有新父母现有的孩子以与前者进行比较。我想检查是否删除的项目已作为新父项的子项存在。
    • @ProfP30 然后获取事件的mimedata信息,例如创建一个fake_model(作为本解决方案中的一个实现:stackoverflow.com/a/55740109/6622587)并获取项目。
    • 谢谢。通过super().dropEvent(event)插入后,如何设置这个新插入的项目的图标?
    猜你喜欢
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多