Reputation: 895
My sample code below creates a 2 row x 10 column Grid. The len() of the Grid seems to print the number of widgets within, not the row or column count. How can I get the column count?
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()
I have considered the following:
Problem with (1) is that it seems like it'll be slow when my Grid contains 1000s of children. Problem with (2) is that I don't see a documented signal for this purpose.
Upvotes: 3
Views: 2200
Reputation: 43276
The grid doesn't store the number of columns anywhere, so it's not easy to retrieve. Internally, the grid simply associates a left-attach and a width property with each child widget.
The easiest way to calculate the number of columns in the grid is to iterate over all its children and find the maximum of 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
Another option would be to subclass Gtk.Grid
and override all methods that add, remove, or move child widgets:
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...
The problem with this is the sheer number of methods that you have to override: add
, attach
, attach_next_to
, insert_column
, remove_column
, insert_next_to
, remove
, and possibly a few more that I've missed. It's a lot of work and prone to errors.
There are events for when child widgets are added or removed from a container, but that doesn't really help - what you really need to intercept is when a child widget's properties are modified, and as far as I know there's no way to do that. I tried to override the child_set_property
method, but it never gets called.
Upvotes: 1