In this PyQt5 Tutorial we are going to learn how to Build Drag & Drop Application in PyQt5,
drag and drop provides a simple visual mechanism which users can use to transfer information
between and within applications. Drag and drop is similar in function to the clipboard’s cut and
paste mechanism. Drag and drop operations are also supported by many of Qt’s controls,
such as the item views and graphics view framework, as well as editing controls for Qt
Widgets and Qt Quick.
Drag and Drop Classes
There are different classes that you can use for Drag & Drop in PyQt5.
QDrag | Support for MIME-based drag and drop data transfer |
QDragEnterEvent | Event which is sent to a widget when a drag and drop action enters it |
QDragLeaveEvent | Event that is sent to a widget when a drag and drop action leaves it |
QDragMoveEvent | Event which is sent while a drag and drop action is in progress |
QDropEvent | Event which is sent when a drag and drop action is completed |
- PyQt5 Tutorial – Build GUI in Python with PyQt5
- TKinter Tutorial -Build GUI in Python with TKinter
- Python Speech Recognition For Beginners
- PyQtGraph Tutorial in Python
After importing the required classes from PyQt5, first we need to create two QListWidgets,
because we want to perform our drag and drop functionalities in the QListWidgets.
1 2 |
self.myListWidget1 = QListWidget() self.myListWidget2 = QListWidget() |
Also we are going to set the QListWidget mode to IconMode.
1 |
self.myListWidget2.setViewMode(QListWidget.IconMode) |
In here we need to enable PyQt5 Drag and Drop functionalities for the QListWidget.
1 2 3 4 |
self.myListWidget1.setAcceptDrops(True) self.myListWidget1.setDragEnabled(True) self.myListWidget2.setAcceptDrops(True) self.myListWidget2.setDragEnabled(True) |
We need to create an HBoxLayout, and we are going to add our QListWidget in QHBoxLayout.
1 2 3 |
self.myLayout = QHBoxLayout() self.myLayout.addWidget(self.myListWidget1) self.myLayout.addWidget(self.myListWidget2) |
We are going to add some items in our first ListWidget.
1 2 3 4 5 6 7 8 |
l1 = QListWidgetItem(QIcon('gym.png'), "GYM") l2 = QListWidgetItem(QIcon('volleyball.png'), "Volleyball") l3 = QListWidgetItem(QIcon('swimming.png'), "Swimming") self.myListWidget1.insertItem(1, l1) self.myListWidget1.insertItem(2, l2) self.myListWidget1.insertItem(3, l3) |
Also we want to do the same for our second ListWidget.
1 2 3 4 5 6 |
QListWidgetItem(QIcon('tennis.png'), "Tennis", self. myListWidget2) QListWidgetItem(QIcon('football.png'), "Football", self. myListWidget2) QListWidgetItem(QIcon('cricket.png'), "Cricket", self. myListWidget2) |
Run the complete code and this is the result.