2

Guess we have TreeView which contain a TreeStore here is my code :

#!/usr/bin/python
# coding=utf-8
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class TreeStore(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(200, 200)
        self.connect("destroy", Gtk.main_quit)

        mylist = ["1","2","3","4","5"]

        scrolledwindow = Gtk.ScrolledWindow()
        scrolledwindow.set_hexpand(True)
        scrolledwindow.set_vexpand(True)
        self.add(scrolledwindow)

        treestore = Gtk.TreeStore(str)
        ListOne = treestore.append(None, ["List One"])
        ListTwo = treestore.append(None, ["List Two"])
        ListThree = treestore.append(None, ["List Three"])


        treeview = Gtk.TreeView()
        treeview.set_model(treestore)
        scrolledwindow.add(treeview)

        cellrenderertext = Gtk.CellRendererText()

        treeviewcolumn = Gtk.TreeViewColumn("Lists")
        treeview.append_column(treeviewcolumn)
        treeviewcolumn.pack_start(cellrenderertext, True)
        treeviewcolumn.add_attribute(cellrenderertext, "text", 0)

        for listItem in mylist:
            treestore.append(ListOne, [listItem])

        treestore.append(ListTwo, ["foo"])
        treestore.append(ListTwo, ["Fido"])
        treestore.append(ListThree, ["Spot"])

window = TreeStore()
window.show_all()

Gtk.main()

then here's the output
enter image description here
For example here i have selected Fido from List Two, how could i get selected, exactly get and print Fido in terminal?

oldtechaa
  • 1,463
  • 1
  • 14
  • 26
  • As was suggested on your last question, please do not use irrelevant tags such as `pygtk` on your questions. Also, if the answer to your previous question helped you (as you're using it in your code) please accept the answer. – oldtechaa May 09 '16 at 18:53

1 Answers1

2

First you need to get the associated TreeSelection object. Then you can use get_selected_rows() to get a list of treepaths pointing to the selected items. Use those treepaths to retrieve the text and you're done.

treestore, selected_treepaths= treeview.get_selection().get_selected_rows()
selected_treepath= selected_treepaths[0] # only one row can be selected
selected_row= treestore[selected_treepath]
text= selected_row[0] # index 0 because this is a TreeStore with only one item of type str
print text

Update: To run this code whenever the selection changes, add this code to your constructor:

class TreeStore(Gtk.Window):
    def __init__(self):
        ...
        treeview.connect('cursor-changed', self.selection_changed)

That will call this function every time the selection updates:

def selection_changed(self, treeview):
    treestore, selected_treepaths= treeview.get_selection().get_selected_rows()
    selected_treepath= selected_treepaths[0] # only one row can be selected
    if len(selected_treepath)==1: # check if a toplevel node is selected
        # get a TreeIter to iterate over all children
        treeiter= treestore.get_iter(selected_treepath)
        treeiter= treestore.iter_children(treeiter)
        children= []
        while treeiter:
            children.append(treestore[treeiter][0]) # treestore[treeiter] gives us the row,
                                                    # [0] gives us the text in that row
            treeiter= treestore.iter_next(treeiter) # move on to the next child
        print ','.join(children)
    else: # not a toplevel node
        selected_row= treestore[selected_treepath]
        text= selected_row[0] # index 0 because this is a TreeStore with only one item of type str
        print text

This will check if a toplevel node (List One, List Two, List Three) is selected, and print out the relevant items. The relevant documentation (for TreeIters and TreePaths) can be found here.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • but where i include that part sir?? because when i try it, it give me an error say `selected_treepath= selected_treepaths[0] # only one row can be` `selected` `IndexError: list index out of range` – Ahmed Bouabid May 09 '16 at 18:02
  • @AhmedBouabid When do you want to print Fido to the terminal? The error is probably because you put the code into the constructor of your TreeStore class. At that time no selection exists yet. – Aran-Fey May 09 '16 at 18:55
  • ,when i run the code will gonna show me as this way `> List One` then if i click on list one item gonna show me 1,2,3,4,5 the liststore of my item. also we have the second list is `> List two` inside her i have foo and Fido ,`> List Three` contain spot ..etc so i need to print each selected Row of all listStore when ever is clicked for example if i click 1 show me 1 is clicked, if i click Fido show me Fido is clicked , if i click Spot ... show me spot is clicked .....etc on this way – Ahmed Bouabid May 09 '16 at 19:16
  • @AhmedBouabid Answer updated. Please try to mention _all_ your requirements in your original question next time. Your question contains nothing about "print every time the selection changes" or "print 1,2,3,4,5". – Aran-Fey May 10 '16 at 06:27