Search code examples
python-2.7pygtk

PyGtk: Forming a a TreeStore from a double list


I am trying to make a tree store from a double list using PyGtk. This is how I did it.

class PyApp(gtk.Window): 
    def __init__(self):
        super(PyApp, self).__init__()

        self.set_size_request(400, 300)
        self.set_position(gtk.WIN_POS_CENTER)

        self.connect("destroy", gtk.main_quit)
        self.set_title("Tree")

        tree = gtk.TreeView()

        languages = gtk.TreeViewColumn()
        languages.set_title("Files")

        cell = gtk.CellRendererText()
        languages.pack_start(cell, True)
        languages.add_attribute(cell, "text", 0)

        treestore = gtk.TreeStore(str)

        doubleL = [['123', 'user1', 'Thisone' 'its.zip'],
        ['Kafueta', 'user1', 'zippedtto.zip'],
        ['Mohm', 'user1', 'zippedtto.zip'],
        ['Hom', 'user2', 'Iam.zip'], 
        ['abcd', 'test', 'Letsee.zip']]

        for lis in doubleL:
            par = treestore.append(None, [lis[0]])
            two = treestore.append(par, [lis[1]])
            treestore.append(two, [lis[2]])

        tree.append_column(languages)
        tree.set_model(treestore)

        self.add(tree)
        self.show_all()

This generates a treestore that can be displayed on a GUI as below. But as you can see, this is not very effective if I have a list with more elements in it. This for loop can be very long:

for lis in doubleL:
    par = treestore.append(None, [lis[0]])
    two = treestore.append(par, [lis[1]])
    treestore.append(two, [lis[2]]

Is there a more effective way I can use in the above for loop to create the tree? enter image description here


Solution

  • This looks like a perfect case for reduce():

    reduce(lambda x, y: treestore.append(x, [lis[y]]), range(len(lis)), None)
    

    In reduce, the x in the above lambda is essentially nested within the previous, making it equivalent to the following in your case.

    treestore.append(treestore.append(treestore.append(None, [lis[0]]), [lis[1]]), [lis[2]])