from gi.repository import Gtk, Gdk, GObject

DRAG_ACTION = Gdk.DragAction.COPY

class DragDropWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title='DnD TreeView Error')

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        hbox = Gtk.Box(spacing=12)
        vbox.pack_start(hbox, True, True, 0)

        self.iconview = DragSourceIconView()
        self.drop_area = DropArea()

        hbox.pack_start(self.iconview, True, True, 0)
        hbox.pack_start(self.drop_area, True, True, 0)

        self.drop_area.drag_dest_add_text_targets()
        self.iconview.drag_source_add_text_targets()

class DragSourceIconView(Gtk.TreeView):

    def __init__(self):
        Gtk.TreeView.__init__(self)

        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Text", renderer, text=0)
        self.append_column(column)

        model = ListModel()
        self.set_model(model)
        self.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [],
            DRAG_ACTION)

class ListModel(Gtk.ListStore, Gtk.TreeDragSource):

    def __init__(self):
        GObject.GObject.__init__(self)
        Gtk.ListStore.__init__(self, str)

        self.add_item("Item 1")
        self.add_item("Item 2")
        self.add_item("Item 3")

    def add_item(self, text):
        self.append([text])

    def do_drag_data_get(self, path, selection):
        text = self[path][0]
        print 'Putting "{}" in drop selection'.format(text)
        selection.set_text(text, -1)
        print 'Set selection to "{}", hope it gets there!'.format(selection.get_text())


class DropArea(Gtk.Label):

    def __init__(self):
        Gtk.Label.__init__(self,
            "Drop something on me!\nI'll print to console.")
        self.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
        self.connect("drag-data-received", self.on_drag_data_received)

    def on_drag_data_received(self, widget, drag_context, x,y, data,info, time):
        text = data.get_text()
        print("Received text: %s" % text)

win = DragDropWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
