在 GtkTreeView 中访问“列”比乍一看要复杂一些。原因之一是列实际上可以包含多个项目,然后显示为新列,即使它们是“打包”的。
识别列的一种方法是为每个列分配一个 sort_id,但这会使标题可点击,如果排序实际上不起作用,这是不自然的。
我设计了这个(有点迂回的)方法:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# test_coord.py
#
# Copyright 2016 John Coppens <john@jcoppens.com>
#
# This program is free software```; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
super(MainWindow, self).__init__()
self.connect("destroy", lambda x: Gtk.main_quit())
trview = Gtk.TreeView()
tstore = Gtk.ListStore(str, str, str)
renderer = Gtk.CellRendererText()
for i in range(3):
col = Gtk.TreeViewColumn("Col %d" % i, renderer, text = i)
col.colnr = i
trview.append_column(col)
trview.set_model(tstore)
trview.connect("button-press-event", self.on_pressed)
for i in range(0, 15, 3):
tstore.append((str(i), str(i+1), str(i+2)))
self.add(trview)
self.show_all()
def on_pressed(self, trview, event):
path, col, x, y = trview.get_path_at_pos(event.x, event.y)
print("Column = %d, Row = %s" % (col.colnr, path.to_string()))
def run(self):
Gtk.main()
def main(args):
mainwdw = MainWindow()
mainwdw.run()
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
这里的诀窍是利用Python 提供的可能性向现有类添加属性。所以我在每一列中添加了一个colnr,并用它来识别点击的单元格。在 C++ 中,必须使用 set_data 和 get_data 方法来做同样的事情(Python 中不可用)。