如何防止 Gtk.Switch 在 Gtk.Grid 内扩展?

How to prevent Gtk.Switch from expanding inside a Gtk.Grid?

在下面的示例代码中,我有一个包含 Gtk.Switch 的 2 列 Gtk.Grid。如何防止此开关填满整个单元格?

#!/bin/python3
import gi

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

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Foo")
        self.set_border_width(12)

        my_grid = Gtk.Grid()
        my_grid.set_column_spacing(12)
        my_grid.set_row_spacing(6)
        self.add(my_grid)

        first_label = Gtk.Label(label="a first label")
        first_label.set_xalign(1)
        my_grid.add(first_label)
        my_button = Gtk.Button(label="a button quite large")
        my_grid.add(my_button)

        second_label = Gtk.Label(label="a second label")
        second_label.set_xalign(1)
        my_grid.attach(second_label, 0, 1, 1, 1)
        my_switch = Gtk.Switch()
        my_grid.attach(my_switch, 1, 1, 1, 1)

win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

谢谢!

再次阅读后默认Gtk-3.0 documentation I found that widgets have a property called halign which in this case seems to have value FILL

解决方案是简单地添加以下行以指示 halign 应该是 START 用于开关:

my_switch.set_halign(Gtk.Align(1))

那里发生的事情是使用 attach():

my_grid.attach(my_switch, 1, 1, 1, 1)

将对齐标志设置为Gtk.Align.FILL

添加以下内容

my_switch.props.halign = Gtk.Align.START

将确保开关不会填满整个space,您可以根据需要使用Gtk.Align.CENTER或Gtk.Align.END。