如何更改 GTK 容器小部件的大小?

fos*_*dom 2 python pygobject gio gtk3

我对 Gtk 如何控制容器(例如 GtkBox)内的小部件大小感到非常困惑。请有人指导我解决这个问题的复杂性吗?

我有一个包含两个小部件的 GtkBox - 在示例中,这些只是两个 GtkButton。

第一个小部件应该只填充 GtkBox 容器内的可用空间。

我想强制的第二个小部件始终是一个物理正方形 - 因此随着正方形的扩大,第一个小部件的宽度将缩小。

一些示例代码将在这里有所帮助:

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()
Run Code Online (Sandbox Code Playgroud)

当您展开窗口时 - GtkBox 也会展开。那挺好的。第一个按钮也同样展开。也好。然而,即使我对 GtkWidget使用set_allocation方法,第二个按钮也永远不会是方形的。

我不能使用 set_size_request (或者我可以吗?)因为当我缩小窗口时,由于第二个按钮的最小尺寸改变,窗口无法调整大小。

我试图弄清楚容器如何管理间距的原因是我希望最终实现像这个 iTunes 示例这样的东西:

在此处输入图片说明

即你可以看到封面总是方形的 - 但音乐细节会根据可用空间缩小或扩大。

pto*_*ato 5

而不是Gtk.Box,使用Gtk.Grid并设置您打包到网格中的按钮上的hexpandvexpand属性。

另外,请考虑Gtk.AspectFrame对方形按钮使用 a 。