Re: [PyGObject] Drag & Drop in a TreeView
- From: Reuben Rissler <silrep emypeople net>
- To: "c.buhtz--- via gtk-app-devel-list" <gtk-app-devel-list gnome org>
- Subject: Re: [PyGObject] Drag & Drop in a TreeView
- Date: Mon, 23 Jul 2018 08:03:15 -0400
On 07/22/2018 04:26 PM, c.buhtz--- via gtk-app-devel-list wrote:
I am totally confused about this topic. I think I miss some fundamental
understanding on how PyGObject works here.
I want to drag & drop items of one TreeView inside itself. Not other
widgets or applications. I just want to drag item 2 and drop it between
item 4 and 5.
<snip>
This is how I have done it in the past. Note, I do not proclaim
spectacular or Pythonic code, and would humbly accept any corrections
and/or better ways to accomplish this. It seems to me there should be a
way to let the TreeView do this work itself, but alas, I have not found
it yet.
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="TreeView Drag and Drop")
self.connect("delete-event", Gtk.main_quit)
self.set_default_size(400, 300)
# "model" with dummy data
self.store = Gtk.TreeStore(str, str)
for i in range(5):
self.store.append(None, ['Item {}'.format(i),
'{}'.format(i*100)]) # treeview
self.view = Gtk.TreeView(model=self.store)
self.add(self.view)
# build columsn
colA = Gtk.TreeViewColumn('Col A', Gtk.CellRendererText(), text=0)
self.view.append_column(colA)
colB = Gtk.TreeViewColumn('Col B', Gtk.CellRendererText(), text=1)
self.view.append_column(colB)
# DnD events
self.view.connect("drag-data-received", self.drag_data_received)
self.view.connect("drag-data-get", self.drag_data_get)
target_entry = Gtk.TargetEntry.new('text/plain', 2, 0)
self.view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK,[target_entry],
Gdk.DragAction.DEFAULT|Gdk.DragAction.MOVE)
self.view.enable_model_drag_dest([target_entry],Gdk.DragAction.DEFAULT|Gdk.DragAction.MOVE)
def drag_data_get (self, treeview, drag_context, data, info, time):
model, path = treeview.get_selection().get_selected_rows()
data.set_text(str(path[0]), -1)
def drag_data_received (self, treeview, drag_context, x,y,
data,info, time):
store = treeview.get_model()
source_path = data.get_text()
source_iter = store.get_iter(source_path)
dest_path = self.view.get_dest_row_at_pos(x, y)
if dest_path != None:
dest_iter = store.get_iter(dest_path[0])
if dest_path[1] == Gtk.TreeViewDropPosition.BEFORE:
store.move_before(source_iter, dest_iter)
else:
store.move_after(source_iter, dest_iter)
treeview.emit_stop_by_name("drag-data-received")
win = MainWindow()
win.show_all()
Gtk.main()
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]