我下面的示例代码创建了一个 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()
我考虑了以下几点:
- 遍历子部件并找到 MAX(width + column)
- 连接到添加列并更新计数器时发出的 Gtk.Grid 信号。
(1) 的问题在于,当我的网格包含 1000 个子项时,它看起来会很慢。 (2) 的问题是我没有看到用于此目的的记录信号。
请您参考如下方法:
网格不会在任何地方存储列数,因此不容易检索。在内部,网格只是关联一个 left-attach。和一个 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 , attach , attach_next_to , insert_column , remove_column , insert_next_to , remove ,可能还有一些我错过的。这是一项繁重的工作,而且容易出错。
当子部件为 added 时,有事件或 removed从容器中获取,但这并没有真正的帮助 - 您真正需要拦截的是子窗口小部件的属性何时被修改,据我所知没有办法做到这一点。我试图覆盖 child_set_property方法,但它永远不会被调用。
