Supporting drag and drop
Many applications allow users to open files by dragging a file from the operating system and dropping it in the application. wxPython, of course, provides support for this as well, through its controls using DropTargets
. This recipe will show how to set up a DropTarget
to allow handling the dragging and dropping of files in an application.
How to do it…
- First, let's create a drop target object to accept files that are dragged over and dropped in the application with the following code:
class MyFileDropTarget(wx.FileDropTarget): def __init__(self, target): super(MyFileDropTarget, self).__init__() self.target = target def OnDropFiles(self, x, y, filenames): for fname in filenames: self.target.AppendText(fname)
- Next, all that is left is to connect the drop target to the window that should accept the dropped file(s). An example of this is shown in the following code:
class MyFrame(wx.Frame): def __init__(self, parent, title=""): super(MyFrame, self).__init__(parent, title=title) # Set the panel self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.text.AppendText("Drag and drop some files here!") dropTarget = MyFileDropTarget(self.text) self.text.SetDropTarget(dropTarget)
How it works…
Drag and drop functions with the use of DropSources
and DropTargets
. In this case, we wanted to allow files to be dropped in the application, so FileDropTarget
was created and associated with the TextCtrl
window. DropTargets
have several virtual callback functions that can be overridden to intercept different actions during the drag and drop events. As FileDropTarget
is specialized for files, it only required overriding OnDropFiles
, which is called with the list of filenames that were dropped in the application. It is necessary to subclass the drop target in order to intercept and handle the data it receives.
In order for a window to accept drag and drop actions, it must have a DropTarget
set; the DropTarget
then gives feedback on whether the data can be accepted or not as well as handling the reception of the data. Try out the example code with this recipe and you will see the mouse cursor change as you drag a file over; then, try again by dragging some text from another application to see the difference.
There's more…
It's also possible to create more application-specific drag and drop handling if needed for custom datatypes by deriving a custom drop target class from PyDropTarget
. This class provides several more overridable methods to allow the handling of various events during the action. Here's a table explaining this:
Methods |
Description |
---|---|
|
This is called when a drag object enters the window. The |
|
This is called while the object is dragged over the window. It returns a |
|
This is called when the drag object leaves the window. |
|
This is called when the drag object is dropped in the window. This method should return |
|
This is called after the data is accepted in |