Thursday
Feb232012
PyQt and Drag and Drop functionality
Thursday, February 23, 2012 at 10:03PM 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
tagged
Python in
Programming
Python in
Programming 
Reader Comments