网格不会在任何地方存储列数,因此检索起来并不容易。在内部,网格简单地关联一个左附加 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方法,但它永远不会被调用。