12 Set

If you have ever attempted to enable drag & drop with Python and GTK, then you've probably run into the same problem I did. When I would drop an item on a widget, it just would not fire off the signal handler. Very frustrating!!!

However, after some digging around, I found the solution. It's a GTK method that you must call to enable a widget as a drop target. The method is widgetname.drag_dest_set(). See my example below to see how it's used.

Example Code:

This isn't a fully working example, but the code snippets are valid syntax and should be useful in your own program. Good luck!

# Set the type of file that can be dropped
dnd_list = [ ( 'text/uri-list', 0, TARGET_TYPE_URI_LIST ) ]

# Connect a function to handle the drop signal
myTree.connect('drag_data_received', on_drag_data_received)

# IMPORTANT: Set an object as a drop destination, or none of this code will work
myTree.drag_dest_set( gtk.DEST_DEFAULT_MOTION |
dnd_list, gtk.gdk.ACTION_COPY)

# Connect a function to handle the drag motion signal from a goocanvas widget
MyCanvas.connect('drag_motion', on_drag_motion)

# Set the canvas to allow drops from any type of file
MyCanvas.drag_dest_set(0, [], 0)

# Function to handle the drag motion
def on_drag_motion(wid, context, x, y, time):
print " *** motion detected ***"

# Function to handle the drop
def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
print " ((( drop detected ))) "