Custom objects in ListStore/TreeStore
Asked Answered
C

3

6

I have a list L of objects of my class A. This class implements __str__/__repr__, so each object has it's own string representation (not necessary unique). I have a GUI in pygtk, where I have a TreeView widget with only one column. I want to populate it with string representations of the objects in L, but then I want to get selected items as objects, not as string. Is there a way to make TreeView to store list of objects, but display them as stings? If not, then what is the best way to know what objects are selected in the TreeView? The problem also is that depending on some conditions I can populate TreeView not with the whole L, but with some sublist of it, and so indexes of items in TreeView won't correspond to ones in L.

Calcaneus answered 19/7, 2011 at 18:24 Comment(0)
C
6

You could store the object in one column (gobject.TYPE_PYOBJECT) and the string representation in a second column, and then only display the second column in your treeview. Similar to what's done here: http://www.learningpython.com/2006/09/02/extending-our-pygtk-application/

Colburn answered 19/7, 2011 at 19:9 Comment(4)
Thank you for the answer! But I use Glade to make GUI and there is no TYPE_PYOBJECT type in the list of types, and type 'GObject' doesn't work :(Calcaneus
You can define the liststore in your code and still define everything else in Glade. Then just use gtk.TreeView.set_model. That's what the blog post I linked to does.Colburn
@Kirill If you're using Glade you might want to state that in your question. You'll get answers more specific to your problem.Reunion
@Jeremy, sorry, I was inattentive ;) This really solves the problem, thanks!Calcaneus
S
2

If your Glade is 3.7.0 or newer you can type "PyObject" (without the quotes) as the column type for you ListStore. Then use set_cell_data_func to retrieve an object from the model and pass its representation to the CellRenderer as text. No string columns to synchronize and no indexes to worry about.

Siphonophore answered 25/7, 2011 at 12:30 Comment(0)
K
0

If the strings are unique you can use a dictionary to link the strings with the objects by using the strings as keys. In this case you can find the objects by its string.

Katlynkatmai answered 19/7, 2011 at 23:2 Comment(1)
unfortunately, they are not necessary unique. And I wonder if it possible to solve the problem without any additional dicts/lists etc...Calcaneus

© 2022 - 2024 — McMap. All rights reserved.