I'm getting myself thoroughly confused about how Gtk controls widget sizes inside a container such as a GtkBox. Please can someone guide me through the intricacies for this question?
I have a GtkBox containing two widgets - in the example these are just two GtkButtons.
The first widget should just fill the space available inside the GtkBox container.
The second widget I want to force always to be a physical square - thus as the square enlarges, the first widget will shrink in terms of width.
Some example code will help here:
from gi.repository import Gtk
def on_check_resize(window):
boxallocation = mainbox.get_allocation()
width = 0
height = 0
if boxallocation.height >= boxallocation.width:
width = boxallocation.height
height = width
if boxallocation.width >= boxallocation.height:
width = boxallocation.width
height = width
secondbtn_allocation = secondbtn.get_allocation()
secondbtn_allocation.width = width
secondbtn_allocation.height = height
secondbtn.set_allocation(secondbtn_allocation)
win = Gtk.Window(title="Containers Demo")
win.set_border_width(10)
win.connect("delete-event", Gtk.main_quit)
mainbox = Gtk.Box()
firstbtn = Gtk.Button(label="just fills the space")
mainbox.pack_start(firstbtn, True, True, 0)
secondbtn = Gtk.Button(label="square")
mainbox.pack_start(secondbtn, False, True, 1)
win.add(mainbox)
win.connect("check_resize", on_check_resize)
win.show_all()
initial = firstbtn.get_allocation()
initial.height = initial.width
firstbtn.set_size_request(initial.width, initial.height)
Gtk.main()
When you expand the window - the GtkBox will likewise expand. That's good. The first button similarly also expands. Good also. However, the second button never is square even though I'm using the set_allocation method for the GtkWidget.
I cannot use the set_size_request (or could I?) because when I shrink the window, the window cannot resize due to the altered minimum size of the second button.
The reason why I'm trying to figure out how containers manage spacing is that I'm looking to eventually implement something like this iTunes example:
i.e. you can see the cover is always square - but the music details will shrink or expand to depending upon the space available.
Instead of Gtk.Box
, use Gtk.Grid
and set the hexpand
and vexpand
properties on the buttons that you pack into the grid.
Also, consider using a Gtk.AspectFrame
for the square button.