如何在垂直 Gtk.Box 中水平居中 Gtk.Grid?

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

我有一个网格,在框架内包含一些标签,使其看起来像 table。此网格插入到一个垂直的 Box 中,其中直接子标签正确居中(它们以与 Grid 相同的方式包装在框中)。

我的简化代码是这样的:

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()

这是它生成的 GUI:

您必须使用 Alignment 和 Expand properties/methods 来设置子容器的行为。

对于 Gtk.Box,您将两个子项的扩展定义为 True,将填充定义为 False,但第一个是容器 Gtk.Grid。当您将标签添加到网格时,您没有设置任何扩展或填充标志。

不确定调整 window 大小时标签的行为方式,但要使 Gtk.Grid 内的标签水平居中,则可以设置 Gtk.Label水平展开为真或将 Gtk.Grid 对齐设置为居中。

示例 - 将 Gtk.Label 水平扩展设置为 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)

但是,如果您 "grow" 垂直 window,标签将彼此分开。我建议您使用 glade 并同时使用展开和小部件对齐方式。

结果: