Search code examples
gtkgtk3pygtk

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


In the following sample code, I have a 2 columns Gtk.Grid that contains a Gtk.Switch. How can I prevent this switch from filling the entire cell?

#!/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()

Thanks!


Solution

  • What is happening there is that using attach():

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

    will set the alignment flag to Gtk.Align.FILL

    adding the following

    my_switch.props.halign = Gtk.Align.START
    

    Will make sure that the switch does not fill the whole space, you can use Gtk.Align.CENTER or Gtk.Align.END if you prefer.