PyQt File Drag and Drop Implementation

  • Share this:

Code introduction


This function implements file drag and drop functionality in a PyQt application. Users can drag files into the window, and the program will print out the local path of the files.


Technology Stack : PyQt5

Code Type : Function

Code Difficulty : Intermediate


                
                    
def drag_and_drop(target, source):
    from PyQt5.QtWidgets import QApplication, QDrag, QDropTarget
    from PyQt5.QtCore import Qt

    class DragSource(QDrag):
        def __init__(self, widget):
            super().__init__(widget)
            self.setDragAction(Qt.CopyAction)

    class DropTarget(QDropTarget):
        def __init__(self, widget):
            super().__init__(widget)
            self.setAcceptDrops(True)

        def dragEnterEvent(self, event):
            if event.mimeData().hasUrls():
                event.acceptProposedAction()

        def dropEvent(self, event):
            for url in event.mimeData().urls():
                print(f"Drop: {url.toLocalFile()}")

    app = QApplication([])
    widget = QWidget()
    drop_target = DropTarget(widget)

    drag_source = DragSource(widget)
    drag_source.exec_()

    widget.show()
    app.exec_()                
              
Tags: