You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gtk.TreeView中识别被点击的列编号/ID

在Gtk.TreeView中获取点击列的编号/ID(Python Gtk3实现)

我想在Gtk.TreeView中获取被点击列的编号/ID(用Python实现,语言本身不影响问题本质)。查了相关文档和社区资料,大多只提到get_sort_column_id()方法,但我不需要排序功能,只想识别点击的列编号。参考Python Gtk3教程代码实现后,能获取列的多种属性,却拿不到列编号,请问该怎么实现?

附相关代码:

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
software_list = [("Firefox", 2002, "C++"),("Eclipse", 2004, "Java")]
class TreeViewFilterWindow(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.grid = Gtk.Grid()
        self.grid.set_column_homogeneous(True)
        self.grid.set_row_homogeneous(True)
        self.set_default_size(500,200)
        self.add(self.grid)
        self.software_liststore = Gtk.ListStore(str, int, str)
        for software_ref in software_list:
            self.software_liststore.append(list(software_ref))
        self.current_filter_language = None
        self.treeview = Gtk.TreeView(model=self.software_liststore)
        for i, column_title in enumerate(["SW", "Year", "Language"]):
            renderer = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(column_title, renderer, text=i)
            self.treeview.append_column(column)
########
# 这段代码让列可点击,但我怎么识别点击的是哪一列?
            self.treeview.set_headers_clickable(True) # 可能没必要
            column.set_sort_column_id(True)                    # LINE A
            column.set_clickable(True)
            column.connect('clicked', self.column_id, column)
########
        self.scrollable_treelist = Gtk.ScrolledWindow()
        self.grid.attach(self.scrollable_treelist, 0, 0, 8, 10)
        self.scrollable_treelist.add(self.treeview)
        self.show_all()

    def column_id(self, widget, column):
       # 打印选中的列对象
       print('selected column', column)
       # 只有当LINE A存在时才会返回1,否则返回-1
       print(column.get_sort_column_id())
       # 我原本希望这个属性能显示列编号,但并没有
       print(column.get_column_id())

win = TreeViewFilterWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

解决方案

有两种简洁的实现方式:

方法1:创建列时绑定索引值

在循环创建列的过程中,直接将列的索引i作为额外参数传递给点击回调函数,完全不需要依赖排序相关接口:

# 修改循环内的代码段
for i, column_title in enumerate(["SW", "Year", "Language"]):
    renderer = Gtk.CellRendererText()
    column = Gtk.TreeViewColumn(column_title, renderer, text=i)
    self.treeview.append_column(column)
    column.set_clickable(True)
    # 直接传递列索引i作为回调参数
    column.connect('clicked', self.column_id, i)

对应修改回调函数:

def column_id(self, widget, column_index):
    print(f"点击的列编号:{column_index}")

方法2:通过TreeView获取列的位置

如果不想在创建列时绑定索引,也可以在回调函数中通过TreeView的get_columns()方法获取所有列的列表,再查找当前点击列的索引:

def column_id(self, widget, column):
    columns = self.treeview.get_columns()
    column_index = columns.index(column)
    print(f"点击的列编号:{column_index}")

额外注意事项

  • 你代码中的column.set_sort_column_id(True)是错误用法,该方法需要传入ListStore中对应的列索引(整数),而非布尔值,这也是get_sort_column_id()返回异常值的原因。如果不需要排序功能,直接删除这行代码即可。
  • self.treeview.set_headers_clickable(True)是默认设置,无需额外声明。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.07 02:03:10