Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center a Gtk.Grid inside a vertical Gtk.Box?

I have a Grid containing some Labels inside Frames to make it look like a table. This grid is inserted in a vertical Box in which direct child Labels are centered correctly (they are packed in the box in the same way as the Grid).

My simplified code is this:

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

window = Gtk.Window()

g = Gtk.Grid()  # this should be in the horizontal center of the window
g.attach(Gtk.Label("This should be centered but it is not."), 0, 0, 1, 1)

b = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
b.pack_start(g, True, False, 0)  # The same behavior with: b.pack_start(g, True, True, 0)
b.pack_start(Gtk.Label("This label is centered as it should be. Try to resize the window."), True, False, 0)

window.add(b)

window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()

and this is the GUI it produces:

Screenshot of the code example.

like image 938
silviubogan Avatar asked Aug 08 '17 20:08

silviubogan


1 Answers

You must use Alignment and Expand properties/methods to set behaviors of child containers.

With Gtk.Box you defined expand as True and Fill as False for both childs but the first one is a container, Gtk.Grid. When you added the label to the Grid you did not set any expand or fill flags.

Not sure how you want the labels to behave when resizing the window but to have the label which is inside the Gtk.Grid to be centered horizontally then you can set the Gtk.Label horizontal expand as true or set the Gtk.Grid Alignment as Centered.

Example - Setting Gtk.Label horizontal expand as True:

g = Gtk.Grid()  # this should be in the horizontal center of the window
l = Gtk.Label("This should be centered but it is not.")
l.set_hexpand(True)
g.attach(l, 0, 0, 1, 1)

However, if you "grow" the window vertically, the labels will separate from each other. I would suggest that you use glade and play with both expand and widget alignment.

Result: result ui

like image 51
José Fonte Avatar answered Dec 09 '22 14:12

José Fonte