Blog Posts
Navigation
Dynamically adding methods to a class in Python »
Thursday
Feb232012

PyQt and Drag and Drop functionality

I recently started working with PyQt, and I needed to allow the user to drag and drop files paths into a listview widget.  With a little bit of research I was able to get it to work. Below is some sample code of how to setup a class for a List widget that will allow for dragging and dropping.  

class TestListBox(ui.QtGui.QListWidget):
      def __init__(self, type, parent=None):
            super(TestListBox, self).__init__(parent)
            self.setAcceptDrops(True)

      def dragEnterEvent(self, event):
            if event.mimeData().hasUrls:
                  event.accept()
            else:
                  event.ignore()

      def dragMoveEvent(self, event):
            if event.mimeData().hasUrls:
                  event.setDropAction(QtCore.Qt.CopyAction)
                  event.accept()
            else:
                  event.ignore()

      def dropEvent(self, event):
            
            if event.mimeData().hasUrls:
                  event.setDropAction(QtCore.Qt.CopyAction)
                  event.accept()
                  
                  links = []

                  for url in event.mimeData().urls():
                        links.append(str(url.toLocalFile()))
                  
                  self.emit(ui.QtCore.SIGNAL("dropped"), links)
            else:
                  event.ignore()
From there, in your window code you can initialize the list such as self.view = TestListbox(self) .  You must also make sure 
that the listView widget is set as the central widget for the window.  If you do not set it to be the central widget, the drag and
drop functionality does not appear to work.  The last couple of steps is to then connect the drop signal to a function where you
add the list items into the list.  The code above gets the data, but it does not actually add the data as items into the widget.  
To do this add code such as this:

self.connect(self.view, QtCore.SIGNAL("dropped"), self.testDropMethod )

In the function called testDropMethod just add the items to the list. The method should be defined in this way:

def testDropMethod(self, l): (l is the actual list of files that you can iterate through and add as items to the list)

 

I hope this is helpful for anyone who is also trying to do this. There is also a very good post on this here

.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>