rubygtk3gladegtktreeview

Programmatically populating GtkTreeView in Glade created UI


Background

I have a photo gallery generator written in Ruby. Configuration for each photo gallery and the generator itself are both in one YAML file. This tool already works in as a terminal tool. Now I want to create a GUI for this and I chose Gtk as the GUI library. I created rough UI in Glade and I have classes both for Gtk::ApplicationWindow and Gtk::Application. When I run the Ruby code the UI created in Glade really loads / displays. Now I am a bit stuck with populating GTKTreeView, which I want to use to display the config data for a user to make last adjustments before generating the galleries.

I pushed the code I have so far — https://gitlab.com/lipoqil/static-photo-gallery-builder/-/compare/master...gui

What I've tried

I found a lot of examples in C, but those usually don't deal with classes, so those are useless for me.

I also found examples in Ruby which are not using Glade and are building the whole UI programmatically by creating manually instances of Gtk classes and naturally those then have the reference in a variable.

I found a few videos of doing something similar in Python, but those were just attaching actions to buttons, so they didn't need the reference to a specific element in the UI.

Question

How do I get reference to the GTKTreeView / GTKListStore so I can populate it?

What I imagine is I need to call .get_object('<id I've set in Glade>') on something, but have no idea on what.

In case it is not clear from "What I've tried"… I am not looking for example in C or example where the whole UI is done programmatically.

Tools used


Solution

  • I asked ChatGPT 4 and I got a working answer.

    What I was probably looking for was bind_template_child. You give it an ID from the Glade view and after initialisation of the window class, it becomes an instance variable.

    module StaticPhotoGalleryGenerator
      module GUI
        class ApplicationWindow < Gtk::ApplicationWindow
          type_register
    
          class << self
           
            def init
              # Set the template from the resources binary
              set_template resource: '/cz/rooland/static-photo-gallery-generator/ui/application_window.glade'
              bind_template_child('config_store1')
              bind_template_child('generate_button')
            end
          end
    
          def initialize(application)
            super application: application
    
            puts @config_store1.inspect # #<Gtk::ListStore:0x00000001437d1998 ptr=0x0000600000de20b0>
          end
        end
      end
    end
    

    I'll mark this as the answer, but I'll check this question time to time if a human didn't come up with a better solution ;)