Search code examples
pythonpyqtdrag-and-droppysideqtreewidget

Dropping an external file into a QTreeWidget


I guess the implementation isn't quite the same for a QTreeWidget, but I'd like to be able to drop an external file, particularly an image or movie file into my QTreeWidget. I'm not trying to drag it into a specific QTreeWidgetItem, but rather just the tree as a whole. Here's my code:

class moTree(QTreeWidget):
    def __init__(self, parent):
        super(moTree, self).__init__(parent)
        self.setMouseTracking(True)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasUrls:
            for url in event.mimeData().urls():
                #Handle stuff here
        else:
            event.ignore()  

The dragEnterEvent is being called, but the dropEvent is not and I'm getting the 'blocked' icon. Any ideas why?


Solution

  • You need to reimplement QTreeWidget.mimeTypes so that it returns a list of the types you want to support:

    def mimeTypes(self):
        return QtCore.QStringList([
            'text/uri-list',
            'application/x-qabstractitemmodeldatalist',
            ])