Drag and Drop with PyQt4
David Boddie
david at boddie.org.uk
Fri Aug 25 19:27:30 EDT 2006
Harshad wrote:
> When I run the program, DragEnterEvent works as expected, but the
> DropEvent does not seem to be working. I'm not an experienced Python
> hacker, and am unable to trace out any problems with the source code.
> Any and all help will be appreciated!
I'm making an educated guess from memory, but I think you need to
implement your own dragMoveEvent() method and accept the event there
as well. This is because the item view widgets typically like to handle
all aspects of drag and drop, and QListView (from which QListWidget is
derived) ignores drag move events by default.
So, if you want to change the behaviour in a fundamental way, you need
to handle many aspects of the process; in this case, you need to
provide your own dragEnterEvent(), dragMoveEvent() and dropEvent()
methods. These can be simple, as shown in the following example:
class ListWidget(QListWidget):
def __init__(self, parent = None):
QListWidget.__init__(self, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dragMoveEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
print "Drop"
event.accept()
listWidget = ListWidget()
listWidget.show()
I tested this code with Python 2.4.2, Qt 4.1.4 and PyQt 4.1, and I
think you should be able to do the same in your code.
Two other points:
1. If you are prepared to try Qt's model/view classes, you can exert
more control over the way drag and drop is handled. They're not
quite as straightforward as the item-based classes that you're
already using, but you benefit from greater reusability of your
components and better control over the appearance and behaviour
of the view widgets.
This guide is for C++, but it translates fairly well into Python:
http://doc.trolltech.com/4.1/model-view-programming.html
2. You seem to prefer adding methods to specific instances rather than
subclassing and reimplementing methods in the base class. I hope
you don't mind me asking, but is that because it takes less code,
because you find it conceptually easier, or is there another reason
that I'm missing?
David
More information about the Python-list
mailing list