How to access a custom widget's attributes from the main struct?

Hello, World!

I’m creating a custom widget as described in the gtk-rs book.

How can I access CustomButton.number from the CustomButton class in The book doesn’t cover that because .number is only ever used in the other class (in

Let’s say I’m trying to add a method like

pub fn get_number(&self) -> i32 {
    // self.???

Here I only have access to .inner and .phantom. The former is a TypedObjectRef<CustomButton, Button>, which doesn’t give me access to a CustomButton object. The latter is a PhantomData<>, which doesn’t look like what I need.

I’ve checked the Amberol source code to see how a real-life application solves this problems, and it uses .imp(), which comes from ObjectSubclassIsExt (e.g.
src/ · ff850affcba6f46b1d3b7c4a42b95ab52e517ff8 · World / amberol · GitLab).

But I don’t have access to that.

It’s possible that Amberol uses a newer version of glib or GTK but even then, I assume that the version in the book also has a way to do what I’m trying to do? I tried using GTK 4.10, but no dice.

I’m not sure how I didn’t realize that, but it was because I hadn’t explicitly imported the ObjectSubclassIsExt trait. So I just needed to add something like

use gtk::subclass::prelude::ObjectSubclassIsExt;

then I can do self.imp().number if the field is public.

Instead of importing a single trait, you should import the whole subclass prelude:

use gtk::subclass::prelude::*;

This will avoid extra pain in the future.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.