-
Book Overview & Buying
-
Table Of Contents
wxPython Application Development Cookbook
By :
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.
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)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)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.
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 |
Change the font size
Change margin width
Change background colour