In this lesson, we are going to learn how to create the label to listbox drag and drop effect in PyQt5 in Python.

Drag an drop is a very common feature in many applications. Basically you would “grab” an object[s] with your mouse and drop them to a destination object.





Source Code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QListWidget

class ListBox(QListWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.setAcceptDrops(True)

    def mimeTypes(self):
        mimeTypes = super().mimeTypes()
        mimeTypes.append('text/plain')
        return mimeTypes

    def dropMimeData(self, index, data, action):
        if data.hasText():
            self.addItem(data.text())
            return True
        else:
            return super().dropMimeData(index, data, action)

class AppDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 600)

        edit = QLineEdit('', self)
        edit.setDragEnabled(True)
        edit.move(30, 30)

        lstBox = ListBox(self)
        lstBox.move(30, 150)

app = QApplication(sys.argv)

demo = AppDemo()
demo.show()

sys.exit(app.exec_())