PyQt - Drag & Drop

The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another.

MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process.

The following QMimeData class functions allow the MIME type to be detected and used conveniently.

Tester Getter Setter MIME Types
hasText() text() setText() text/plain
hasHtml() html() setHtml() text/html
hasUrls() urls() setUrls() text/uri-list
hasImage() imageData() setImageData() image/ *
hasColor() colorData() setColorData() application/x-color

Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them.

  • DragEnterEvent provides an event which is sent to the target widget as dragging action enters it.

  • DragMoveEvent is used when the drag and drop action is in progress.

  • DragLeaveEvent is generated as the drag and drop action leaves the widget.

  • DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally.


In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox.

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class combo(QComboBox):

   def __init__(self, title, parent):
      super(combo, self).__init__( parent)
   def dragEnterEvent(self, e):
      print e
      if e.mimeData().hasText():
   def dropEvent(self, e):
class Example(QWidget):

   def __init__(self):
      super(Example, self).__init__()
   def initUI(self):
      lo = QFormLayout()
      lo.addRow(QLabel("Type some text in textbox and drag it into combo box"))
      edit = QLineEdit()
      com = combo("Button", self)
      self.setWindowTitle('Simple drag & drop')
def main():
   app = QApplication(sys.argv)
   ex = Example()
if __name__ == '__main__':

The above code produces the following output −

Drag and Drop Output