How to set multiple items into a GtkSelection for

2020-08-01 05:24发布

问题:

My current project uses a Gtk.TreeView to display the contents of a ListView with four fields per row, two strings, an int and a boolean. I'm trying to implement drag and drop rearrangement of rows in the TreeView. I don't want simply to use TreeView.set_reorderable(True) for the built-in drag and drop because I want to have some control over the insertion and deletion of data from the model as well as to be able to implement undo/redo of drag and drop operations. I'm using Python 3.2 and PyGObject 3.

The problem I'm now having is figuring out how in my drag_data_get method to set the selection data object with the two strings, one int and one bool that make up the row to be dragged and dropped. All the example code I've been able to find involves treeviews with a single column with string values that get set into the selection with something like this:

def drag_data_get_data(self, treeview, context, selection, target_id, etime):
    treeselection = treeview.get_selection()
    model, iter = treeselection.get_selected()
    data = bytes(model.get_value(iter, 0), "utf-8")
    selection.set(selection.get_target(), 8, data)

All my efforts to set the selection object with the data from one of my TreeView rows have failed. The int and bool values in my model can't be encoded like string values and I can't find any examples of how to set all the values for a multi-column TreeView row into a single selection object. Can anyone point me to some relevant examples or docs?

回答1:

You could encode your tuple of 4 values into a single string. An easy way is to use json for that:

import json
data = ["string", "string2", True, 20]
string_variable = json.dumps(data)
#
# now pass string_variable through drag and drop
#
returned = json.loads(string_variable)

You could also use your own encoding scheme if importing json is not an option for you.

Please do a careful sanity check on the data you get this way. If you don't, some specially crafted string (passed from another program, say) might crash you program or worse.