How to Drag and Drop from One QListWidget to Another

前端 未结 3 1805
心在旅途
心在旅途 2020-12-05 16:25

There are two QListWIdgets sitting in a same dialog window. The DragDrop functionality has been enabled for both. If I drag and drop a file to any of two ListWidges the prog

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 16:50

    The above code did not work for me, when implementing the Python 3 style of super().

    The issue is that the inherited methods dragMoveEvent and dragDropEvent were not being overwritten with the new definitions in the child class.

    Therefore event.setDropAction(QtCore.Qt.MoveAction) was not being called, and the widget behavior defaulted to QtCore.Qt.CopyAction.

    I solved this using the setDefaultDropAction() method inherited from the QAbstractItemView class.

    Here is the implementation in PyQt5 and Python 3.7:

    class NewDragDropWidget(QListWidget):
    
        def __init__(self):
            super().__init__()
            self.setIconSize(QtCore.QSize(124, 124))
            self.setDragDropMode(QAbstractItemView.DragDrop)
            self.setDefaultDropAction(QtCore.Qt.MoveAction) # this was the magic line
            self.setSelectionMode(QAbstractItemView.ExtendedSelection)
            self.setAcceptDrops(True)
    

提交回复
热议问题