Gtk-rs: access object by id defined in UI XML definition

I am writing an application with a GTK-based UI, following the examples I found in Composite Templates - GUI development with Rust and GTK 4.

What I have is an xml definition of the applications main window elements. This xml file contains a TextView with id 'textview':

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <template class="AppWindow" parent="GtkApplicationWindow">
    <child>
         ...
          <child>
            <object class="GtkTextView" id="textview">
            ...
            </object>
          </child>
        ...
    </child>
  </template>
</interface>

I now would like to use this TextView in my code. For this, I would like to get a reference to the 'TextView (TextView in gtk4 - Rust) based on the XML id I defined.

I thought of doing this somewhere in the instantiation of Window:

Here is the corresponding code part from the example:

#[derive(CompositeTemplate, Default)]
#[template(resource = "/org/gtk_rs/example/window.ui")]
pub struct Window {
    pub number: Cell<i32>,
    pub textview: TextView,       // <== get a reference to the object and store it here
}

// The central trait for subclassing a GObject
#[glib::object_subclass]
impl ObjectSubclass for Window {
    // `NAME` needs to match `class` attribute of template
    const NAME: &'static str = "MyGtkAppWindow";
    type Type = super::Window;
    type ParentType = gtk::ApplicationWindow;

    fn class_init(klass: &mut Self::Class) {
        // Register `CustomButton`
        CustomButton::ensure_type();

        klass.bind_template();
        klass.bind_template_callbacks();
    }

    fn instance_init(obj: &InitializingObject<Self>) {
        obj.init_template();
    }
}

I also found that the is the object method to find a GUI object by its id (Builder in gtk4 - Rust), but I could not figure out how to implements this into the example.

But maybe there are better ways to approach this problem?

(to explain where I am coming from: I used Qt in combination with C++ for many years, and am very familiar with it. There, the link between objects and code is more direct. I am now using Gtk for the first time because I'd like to write a cross-platform application using Rust).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.