如何改变GTK容器小部件的大小?
我对Gtk是怎么控制容器里小部件的大小感到很困惑,比如GtkBox。有没有人能帮我理清这个问题的细节?
我有一个GtkBox,里面放了两个小部件——在这个例子里就是两个Gtk按钮。
第一个小部件应该填满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()
当你扩大窗口时,GtkBox也会随之扩大。这很好。第一个按钮也会相应地扩大,这也不错。但是,第二个按钮却从来没有变成正方形,尽管我使用了set_allocation这个方法。
我不能使用set_size_request(或者我可以吗?),因为当我缩小窗口时,窗口无法调整大小,因为第二个按钮的最小尺寸已经改变了。
我之所以想搞清楚容器是怎么管理间距的,是因为我想最终实现类似于这个iTunes的例子:
也就是说,你可以看到封面始终是正方形的,而音乐的细节会根据可用空间的大小而缩小或扩大。
1 个回答
4
与其使用 Gtk.Box
,不如用 Gtk.Grid
,并且在你放入网格中的按钮上设置 hexpand
和 vexpand
属性。
另外,可以考虑使用一个 Gtk.AspectFrame
来做方形按钮。