GTK TreeView: 20-line minimal script won't sho

2019-09-06 01:23发布

问题:

I've got a simplest TreeView example possible, mostly copied from basictreeview.py, but even simplier, but the TreeView itself won't show inside the toplevel window. What's wrong:

import gtk

class Application(object):
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Alignment Editor")
        self.window.set_default_size(1024, 768)
        self.window.connect("delete_event", lambda w,e: gtk.main_quit())

        self.row = ["a", "b", "c", "d", "e", "f", "g", "h"]
        self.store = gtk.ListStore(*[str]*len(self.row)) #create len(word) columns
        self.store.append(self.row)

        self.treeview = gtk.TreeView(self.store)
        self.treeview.set_reorderable(True)
        self.window.add(self.treeview)
        self.window.show_all()

if __name__ == "__main__":
    Application()
    gtk.main()

回答1:

You are missing TreeviewColumns and CellRenderers, I believe the minimal example is (sorry is GTK3 but it's the same as Pygtk)

from gi.repository import Gtk

class Application(object):
    def __init__(self):
        self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        self.window.set_title("Alignment Editor")
        self.window.set_default_size(200, 150)
        self.window.connect("delete_event", lambda w,e: Gtk.main_quit())

        self.row = ["a", "b"]
        self.store = Gtk.ListStore(*[str]*len(self.row)) #create len(word) columns
        self.store.append(self.row)

        cra = Gtk.CellRendererText()
        twcolumna = Gtk.TreeViewColumn("Column a")
        twcolumna.pack_start(cra, True)
        twcolumna.add_attribute(cra, 'text', 0)

        crb = Gtk.CellRendererText()
        twcolumnb = Gtk.TreeViewColumn("Column b")
        twcolumnb.pack_start(crb, True)
        twcolumnb.add_attribute(crb, 'text', 1)

        self.treeview = Gtk.TreeView(self.store)

        self.treeview.append_column(twcolumna)
        self.treeview.append_column(twcolumnb)

        self.treeview.set_reorderable(True)
        self.window.add(self.treeview)
        self.window.show_all()

if __name__ == "__main__":
    Application()
    Gtk.main()