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

7

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

我的简化代码如下:

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界面:

代码样例的屏幕截图。

1个回答

6

您需要使用对齐和扩展属性/方法来设置子容器的行为。

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

不确定您希望在调整窗口大小时标签如何表现,但要使位于Gtk.Grid内部的标签在水平方向上居中,则可以将Gtk.Label水平扩展设置为true,或将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)

然而,如果您垂直“拉伸”窗口,标签将分离。我建议您使用Glade并尝试扩展和小部件对齐方式。
结果: result ui

这个答案似乎非常特定于仅包含一行、一列和一个项目的网格的情况(使其作为网格有点无意义)。那么当有多个项目、行和列时该怎么办?我应该在哪里设置 hexpand - Jack M
嗨@JackM,新年快乐。这个问题现在有点老了。Gtk已经进入第四个版本(Gtk4),事情可能有所改变。正如上面的答案所示,我建议安装Glade并玩弄小部件及其属性。它还允许在没有代码的情况下运行UI。祝你好运。 - José Fonte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接