获取 Gtk.Grid 中的列数?

2024-01-02

下面的示例代码创建了一个 2 行 x 10 列的网格。 Grid 的 len() 似乎打印其中的小部件数量,而不是行数或列数。如何获得列数?

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

window = Gtk.Window()
window.connect("destroy", Gtk.main_quit)
grid = Gtk.Grid(column_homogenous=True)
for i in range(5):
  grid.add(Gtk.Label(str(i)))
grid.attach(Gtk.Label("123456789A"), 0, 1, 10, 1)
window.add(grid)
window.show_all()
print(len(grid))
Gtk.main()

我考虑过以下几点:

  1. 循环子部件并找到 MAX(宽度 + 列)
  2. 连接到添加列并更新计数器时发出的 Gtk.Grid 信号。

(1) 的问题是,当我的网格包含 1000 个子级时,它看起来会很慢。 (2) 的问题是我没有看到用于此目的的记录信号。


网格不会在任何地方存储列数,因此检索起来并不容易。在内部,网格简单地关联一个左附加 https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#GtkGrid--c-left-attach and a width https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#GtkGrid--c-width每个子部件的属性。

计算网格中列数的最简单方法是迭代其所有子项并找到最大值left-attach + width:

def get_grid_columns(grid):
    cols = 0
    for child in grid.get_children():
        x = grid.child_get_property(child, 'left-attach')
        width = grid.child_get_property(child, 'width')
        cols = max(cols, x+width)
    return cols

另一种选择是子类化Gtk.Grid并重写所有添加、删除或移动子部件的方法:

class Grid(Gtk.Grid):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.columns = 0
    
    def add(self, child):
        super().add(child)
        self.columns = max(self.columns, 1)
    
    def attach(self, child, left, top, width, height):
        super().attach(child, left, top, width, height)
        self.columns = max(self.columns, left+width)

    # etc...

这样做的问题是您必须重写的方法数量巨大:add https://developer-old.gnome.org/gtk3/stable/GtkContainer.html#gtk-container-add, attach https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#gtk-grid-attach, attach_next_to https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#gtk-grid-attach-next-to, insert_column https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#gtk-grid-insert-column, remove_column https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#gtk-grid-remove-column, insert_next_to https://developer-old.gnome.org/gtk3/stable/GtkGrid.html#gtk-grid-insert-next-to, remove https://developer-old.gnome.org/gtk3/stable/GtkContainer.html#gtk-container-remove,可能还有一些我错过的。这是一项繁重的工作并且容易出错。


There are子部件出现时的事件added https://developer-old.gnome.org/gtk3/stable/GtkContainer.html#GtkContainer-add or removed https://developer-old.gnome.org/gtk3/stable/GtkContainer.html#GtkContainer-remove来自容器,但这并没有真正帮助 - 你什么really需要拦截的是当子窗口小部件的属性被修改时,据我所知,没有办法做到这一点。我试图覆盖child_set_property https://developer-old.gnome.org/gtk3/stable/GtkContainer.html#gtk-container-child-set-property方法,但它永远不会被调用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 Gtk.Grid 中的列数? 的相关文章

随机推荐