Search code examples
gtkgtk4

Making a widget that looks like GtkSpinButton


I am building a widget in GTK (just started)

image of an app

Currently structured as

GtkBox(Orientation:Horizontal)
|-GtkEntry
|-GtkButton

but I want it to look like GtkSpinButton.

enter image description here

with the frame wrapping round the entry and the button.

I did try looking into the source code of GtkSpinButton to see how it's done, but I don't see anywhere how it's laid out. If anyone can explain what's going on there that would be much appreciated.

I'm avoiding adding any code as I wanted to keep it as general as possible. Developing in Rust, but I can understand C or feel free to psuedo code.


Solution

  • You can add linked CSS class to the parent GtkBox to make the content as linked as it is in a GtkSpinButton.

    For example, see the following linked.ui file:

    <?xml version="1.0" encoding="UTF-8"?>
    <interface>
    <object id="window" class="GtkWindow">
      <property name="title">Linked Box</property>
    
        <child>
          <object class="GtkBox">
            <property name="halign">center</property>
            <property name="valign">center</property>
            <property name="margin-top">60</property>
            <property name="margin-bottom">60</property>
            <property name="margin-start">60</property>
            <property name="margin-end">60</property>
            <style>
              <class name="linked"/>
            </style>
    
            <child>
              <object class="GtkEntry"/>
            </child>
    
            <child>
              <object class="GtkButton">
                <property name="label">+</property>
              </object>
            </child>
    
          </object> <!-- ./GtkBox -->
        </child>
    
      </object>
    </interface>
    

    Run the above file with gtk4-builder-tool preview linked.ui.

    With C, you can achieve the same with gtk_widget_add_css_class() API.