【问题标题】:How to pass selected Gtk TreeView row to Gtk TreeStore insert function?如何将选定的 Gtk TreeView 行传递给 Gtk TreeStore 插入函数?
【发布时间】:2014-07-31 17:21:22
【问题描述】:

我试图在 Gtk.TreeStore 中插入一行,为此我必须从 Gtk.TreeView 传递选定的行号。我找到了 PyGTK 的解决方案,但没有找到 PyGObject 的解决方案。

对于 PyGTK,插入函数如下所示 (http://www.pygtk.org/pygtk2reference/class-gtktreestore.html#method-gtktreestore--insert):

 def insert(parent, position, row=None)

位置可以这样查询:

 treeview = Gtk.TreeView()
 selection = treeview.get_selection()
 model, iter = selection.get_selected()
 path = iter.get_selected_rows()[0]
 index = path.get_indices()[0]

但是在 PyGObject 中我得到了错误:

self.index = self.path.get_indices()[0]
AttributeError: 'LayerDataStore' object has no attribute 'get_indices'

如何获取行号的整数值?我是否以一种奇怪的方式解决问题?看起来解决方案应该更简单,代码更少。

延伸阅读:

这是GTK3中插入函数的说明:

PyGTK 的类似问题:

C++ 的类似问题:

【问题讨论】:

    标签: gtk3 pygobject


    【解决方案1】:

    终于想通了。但我不确定是否有更简单的解决方案:

    首先在 TreeView 上调用 select:

    tree = Gtk.TreeView()
    select = tree.get_selection()
    

    select 是一个 Gtk.TreeSelection。我们使用这个对象来调用get_selected_rows()

    selected_rows = select.get_selected_rows()
    

    The function returns a tuple of a LayerDataStore and a GtkTreePath when a row is selected.否则 GtkTreePath 是一个空列表 []

    然后将 GtkTreePath 分配给一个变量:

    path = selected_rows[1]
    

    Path 现在是 GtkTreePath列表 或空列表 [] 如果未选择任何内容。您可以在此处插入 if 函数以避免出现任何错误。

    然后我们必须使用以下方法解压列表:

    row = path[0]
    

    现在变量 row 是一个 TreePath,打印函数将返回 0 表示第一行,1 表示第二行,以此类推。对于嵌套树,它将为第一行中的第一个嵌套对象返回 0:0,为第一行中的第二个对象返回 0:1,依此类推。

    通过 get_indices 函数,我们可以将 TreePath 转换为 list

    index = row.get_indices()
    

    打印函数现在将打印第一行的 [0] 和第二行的 [1]。第一行的第一个对象的嵌套对象为 [0,0],第一行的第二个嵌套对象的嵌套对象为 [0,1]。

    因为我只对行号本身感兴趣,所以我使用此分配来仅获取行号:

    row_number = index[0]
    

    最后将行号传递给TreeStore:

    store.insert(None, row_number, [True, "New Layer")])
    

    有用的链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多