我试图在Gtk.TreeStore中插入一行,我必须从Gtk.TreeView传递选定的行号。我找到了PyGTK的解决方案,但没有找到PyGObject的解决方案。
对于PyGTK,insert函数看起来像这样(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 ++的类似问题:
答案 0 :(得分:2)
终于明白了。但我不确定是否有更简单的解决方案:
首先在TreeView上调用select:
tree = Gtk.TreeView()
select = tree.get_selection()
选择然后是 Gtk.TreeSelection 。我们使用此对象来调用 get_selected_rows():
selected_rows = select.get_selected_rows()
当选择行时,该函数返回 LayerDataStore 的元组和 GtkTreePath 。否则, GtkTreePath 是一个空列表 [] 。
然后将 GtkTreePath 分配给变量:
path = selected_rows[1]
如果未选择任何内容,则路径现在是 GtkTreePath 的列表或空列表 [] 。您可以在此处插入if-function以避免出现任何错误。
然后我们必须使用以下方法解压缩列表:
row = path[0]
现在变量行是 TreePath ,打印函数将为第一行返回0,为第二行返回1,依此类推。对于嵌套树,它将为第一行中的第一个嵌套对象返回0:0,对于第一行中的第二个对象返回0:1,依此类推。
使用 get_indices 功能,我们可以将 TreePath 转换为列表:
index = row.get_indices()
打印功能现在将为第一行打印[0],为第二行打印[1]。嵌套对象对于第一行的第一个对象是[0,0],对于第一行的第二个嵌套对象是[0,1]。
因为我只对行号本身感兴趣,所以我使用此赋值只获取行号:
row_number = index[0]
最后,行号被传递给TreeStore:
store.insert(None, row_number, [True, "New Layer")])
有用的链接: