Reputation: 2231
I am trying to insert a row into a Gtk.TreeStore, for which I have to pass the selected row number from Gtk.TreeView. I found the solution for PyGTK but not for PyGObject.
For PyGTK the insert function looks like this (http://www.pygtk.org/pygtk2reference/class-gtktreestore.html#method-gtktreestore--insert):
def insert(parent, position, row=None)
The position can be queried like this:
treeview = Gtk.TreeView()
selection = treeview.get_selection()
model, iter = selection.get_selected()
path = iter.get_selected_rows()[0]
index = path.get_indices()[0]
But in PyGObject I get the error:
self.index = self.path.get_indices()[0]
AttributeError: 'LayerDataStore' object has no attribute 'get_indices'
How can I get the integer value of the row number? Am I approaching the problem in a weird way? It seems like the solution should be simpler and have less code.
This is the description of the insert function in GTK3:
Similar question for PyGTK:
Similar question for C++:
Upvotes: 3
Views: 1250
Reputation: 2231
Finally figured it out. But I am not sure if there is a simpler solution:
First call select on the TreeView:
tree = Gtk.TreeView()
select = tree.get_selection()
select is then a Gtk.TreeSelection. We use this object to call get_selected_rows():
selected_rows = select.get_selected_rows()
The function returns a tuple of a LayerDataStore and a GtkTreePath when a row is selected. Otherwise the GtkTreePath is an empty list [].
Then assign the GtkTreePath to a variable:
path = selected_rows[1]
Path is now a list of the GtkTreePath or an empty list [] if nothing is selected. You can insert an if-function here to avoid getting any Errors.
We then have to unpack the list by using:
row = path[0]
Now the variable row is a TreePath and the print function will return 0 for the first row, 1 for the second row and so on. For nested trees it will return 0:0 for the first nested object in the first row, 0:1 for the second object in the first row and so on.
With the get_indices function we can convert the TreePath to a list:
index = row.get_indices()
The print function will now print [0] for the first row and [1] for the second. The nested objects are [0,0] for the first object of the first row and [0,1] for the second nested object of the first row.
Because I am just interested in the row number itself I am using this assignment to get only the row number:
row_number = index[0]
Finally the row number is passed to the TreeStore:
store.insert(None, row_number, [True, "New Layer")])
Helpful links:
Upvotes: 2