Search code examples
pyqt

How to make PyQT drag event copy a file instead of move it?


I have a little python app that searches the file system for files, and lets you drag them out of a QListWidget and into other software, your desktop, etc.

The problem is, I don't ever want to destroy/remove the source file. If I drag the file onto my desktop, I want to keep the file in the source location as well.

Currently, I'm creating a QDrag event and attaching mime data for the file. How do I tell windows that this is a copy/paste situation rather than a cut/paste situation?

class MyListWidget(QListWidget):
    ...
    def dragLeaveEvent(self, event):
        global window
        drag = QDrag(self)
        data = QMimeData()
        data.setData("text/plain", "")

        files = []
        # Loop through QList (file paths), turn into QUrl, and add to array
        for element in window.searchResults.selectedIndexes():
            url = element.data()
            files.append(QUrl.fromLocalFile(url)

        data.setUrls(files)
        drag.setMimeData(data)
        drag.exec_()

Solution

  • In PyQt6 that would be:

    drag.exec(QtCore.Qt.DropAction.CopyAction)