xmlgtkgtk4

Put one child at the beginning and one child and the end of `GtkBox` in GTK4 using XML


The title pretty much describes the problem. I know I can start packing elements from the beginning or end of an element (GtkBox, for example) using the pack_start and pack_end functions programmatically. But I want to use XML.

I can't use halign / valign because they affect all children at once.

I tried using <child type="[start/end]"> like for AdwHeaderBar's children, but they don't work for GtkBox.

I haven't found much documentation on GTK4's XML packing syntax.

My question is mostly the same as this, but for GTK4 since the packing syntax was dropped in the transition from GTK3 to GTK4.


Solution

  • For this task, I recommend the GTKCenterBox class. Here is an example of the .ui file.

    <?xml version='1.0' encoding='UTF-8'?>
    <interface>
      <!-- interface-name packtyp.ui -->
      <requires lib="gtk" version="4.0"/>
      <object class="GtkWindow" id="window">
        <property name="title">PackTyp right and left Gtk4</property>
        <child>
          <object class="GtkCenterBox" id="box">
            <property name="orientation">GTK_ORIENTATION_HORIZONTAL</property>
            <child type="start" >
              <object class="GtkButton" id="child1">
                  <property name="label">left</property>
              </object>
             </child>
             <child type="end" >
               <object class="GtkButton" id="child2">
                  <property name="label">right</property>
              </object>
             </child>
          </object>
         </child>
      </object>
    </interface>
    

    enter image description here

    best regards