Skip to content Skip to sidebar Skip to footer

Pyqt Drag And Drop Outside App Into Windows File Explorer?

I would like to create files by dragging from a QListWidget into the OS file explorer (Windows 10 in my case), is this possible? So in the widget below, I want dragging 'one' and '

Solution 1:

You need to implement the startDrag() method and add the urls to the QDrag instance.

class DragTest(QtWidgets.QListWidget):
    # ...
    def startDrag(self, actions):
        drag = QtGui.QDrag(self)
        indexes = self.selectedIndexes()
        mime = self.model().mimeData(indexes)
        urlList = []
        for index in indexes:
            urlList.append(QtCore.QUrl.fromLocalFile(index.data()))
        mime.setUrls(urlList)
        drag.setMimeData(mime)
        drag.exec_(actions)

Note that I'm just using the index.data() since you used the full path for the item name, but you might prefer to set a specific data role for the full url in case, for example, you want to show only the file name:

FullPathRole = QtCore.Qt.UserRole + 1classDragTest(QtWidgets.QListWidget):
    # ...defdropEvent(self, e):
        if e.mimeData().hasUrls():
            e.setDropAction(QtCore.Qt.CopyAction)
            e.accept()
            fpath_list = []
            for url in e.mimeData().urls():
                fpath_list.append(str(url.toLocalFile()))

            for fpath in fpath_list:
                print(f'IMPORT {fpath}')
                fileName = QtCore.QFileInfo(fpath).fileName()
                item = QtWidgets.QListWidgetItem(fileName)
                item.setData(FullPathRole, fpath)
                self.addItem(fpath)

    defstartDrag(self, actions):
        # ...
            urlList.append(QtCore.QUrl.fromLocalFile(index.data(FullPathRole)))

Also note that you are missing the parentheses in the if e.mimeData().hasUrls(): check.

Post a Comment for "Pyqt Drag And Drop Outside App Into Windows File Explorer?"