Python GTK+ 3:如何在 TreeView 中设置行活动

Python GTK+ 3: How to set row in TreeView active

我有一个 Gtk.ComboBoxText 应该用作触发器来激活 Gtk.TreeView 中的一行。我知道如何通过激活树视图中的相应行来触发组合框。但反之亦然超出了我的范围。我了解到我需要将 Gtk.TreePath 和 Gtk.TreeViewColumn 传递给函数 row_activated(),但我不知道如何正确实现这些以及将行 ID 放在我的何处函数 self.combo_changed()。这是问题的示例:

from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)

        self.set_default_size(200, 100)
        self.set_border_width(10)

        self.grid = Gtk.Grid(row_spacing=10)
        self.add(self.grid)

        self.combo = Gtk.ComboBoxText()
        self.combo.connect("changed", self.combo_changed)
        self.grid.attach(self.combo, 0, 0, 1, 1)

        self.liststore = Gtk.ListStore()
        self.liststore.set_column_types([int, str])
        self.treeview = Gtk.TreeView(self.liststore)
        self.treeview.set_activate_on_single_click(True)
        self.treeview.connect('row-activated', self.list_changed)
        self.grid.attach(self.treeview, 0, 1, 1, 1)

        cols = ["ID", "Animal"]
        self.treeviewcolumn = []
        self.cellrenderertext = []
        for i in range(len(cols)):
            self.cellrenderertext.append(Gtk.CellRendererText())
            self.treeviewcolumn.append(Gtk.TreeViewColumn(cols[i]))
            self.treeviewcolumn[i].pack_start(self.cellrenderertext[i], True)
            self.treeviewcolumn[i].add_attribute(self.cellrenderertext[i], "text", i)
            self.treeview.append_column(self.treeviewcolumn[i])

        animals = ["Dog", "Cat", "Mouse"]
        self.rowiter = []
        for i in range(len(animals)):
            self.combo.append_text(animals[i])
            self.rowiter.append([self.liststore.append([i, animals[i]])])
        self.combo.set_active(0)

    def list_changed(self, widget, row, data2):
        self.combo.set_active(int(row.to_string()))

    def combo_changed(self, widget):
        print(widget.get_active())  # the ID of the requested row
        #self.treeview.row_activated(Gtk.TreePath(), Gtk.TreeViewColumn())

    def quit_window(self, widget, data=None):
        Gtk.main_quit()

win = MainWindow()
win.show_all()
win.connect("delete-event", win.quit_window)
Gtk.main()

我发现我还需要Gtk.TreeView.set_cursor()来实现我的目标:

def combo_changed(self, widget):
    row = widget.get_active()  # the ID of the requested row
    print(row)
    self.treeview.row_activated(Gtk.TreePath(row), Gtk.TreeViewColumn(None))
    self.treeview.set_cursor(Gtk.TreePath(row))