当用户单击TreeView中的单元格时,是否有一种有效的方法/方法来检索ListModel中所选单元格的列?还是没有诸如单元格之类的东西,当我调用get_selected()方法时,只能选择行并返回其treeiter /模型?

我想向用户展示一个数值矩阵,并允许他选择一列,然后将这些值绘制出来。

如果您手边有任何文档/示例,请随时分享:)

编辑:我试图做的是将列标题上的clicked事件连接到一个函数,该函数为我提供创建过程中在列文本中编码的列号。但这似乎不太正确。

如果有帮助,我可以创建一个最小的工作示例。

最佳答案

在GtkTreeView中访问“列”比乍一看要复杂一些。原因之一是,列实际上可以包含多个项目,即使它们被“打包”,也将显示为新列。

识别列的一种方法是为每个列分配一个sort_id,但这将使标题可点击,如果排序实际上不起作用,则这是不自然的。

我设计了这个(有点曲折)的方法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_coord.py
#
#  Copyright 2016 John Coppens <[email protected]>
#
#  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_dataget_data方法执行相同的操作(Python中不可用)。

关于python - Gtk3 + Pygobject在TreeView中选择列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38057144/

10-09 17:17