From bddbc658e84dc7a625906cbcc48932f49031937e Mon Sep 17 00:00:00 2001 From: ranfdev Date: Tue, 25 Jul 2023 15:19:32 +0200 Subject: [PATCH] Add object_subclass example --- examples/Cargo.toml | 4 +++ examples/object_subclass/author.rs | 49 ++++++++++++++++++++++++++++++ examples/object_subclass/main.rs | 14 +++++++++ 3 files changed, 67 insertions(+) create mode 100644 examples/object_subclass/author.rs create mode 100644 examples/object_subclass/main.rs diff --git a/examples/Cargo.toml b/examples/Cargo.toml index b91f0be5f0f2..57565e204aa6 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -44,3 +44,7 @@ path = "gio_task/main.rs" [[bin]] name = "gio_cancellable_future" path = "gio_cancellable_future/main.rs" + +[[bin]] +name = "object_subclass" +path = "object_subclass/main.rs" diff --git a/examples/object_subclass/author.rs b/examples/object_subclass/author.rs new file mode 100644 index 000000000000..145f484e9a40 --- /dev/null +++ b/examples/object_subclass/author.rs @@ -0,0 +1,49 @@ +// You can copy/paste this file every time you need a simple GObject +// to hold some data + +use glib::once_cell::sync::Lazy; +use glib::prelude::*; +use glib::subclass::prelude::*; +use glib::subclass::Signal; +use glib::Properties; +use std::cell::RefCell; + +mod imp { + use super::*; + + #[derive(Properties, Default)] + #[properties(wrapper_type = super::Author)] + pub struct Author { + #[property(get, set)] + name: RefCell, + #[property(get, set)] + surname: RefCell, + } + + #[glib::derived_properties] + impl ObjectImpl for Author { + fn signals() -> &'static [Signal] { + static SIGNALS: Lazy> = + Lazy::new(|| vec![Signal::builder("awarded").build()]); + SIGNALS.as_ref() + } + } + + #[glib::object_subclass] + impl ObjectSubclass for Author { + const NAME: &'static str = "Author"; + type Type = super::Author; + } +} + +glib::wrapper! { + pub struct Author(ObjectSubclass); +} +impl Author { + pub fn new(name: &str, surname: &str) -> Self { + glib::Object::builder() + .property("name", name) + .property("surname", surname) + .build() + } +} diff --git a/examples/object_subclass/main.rs b/examples/object_subclass/main.rs new file mode 100644 index 000000000000..24ce9663dc72 --- /dev/null +++ b/examples/object_subclass/main.rs @@ -0,0 +1,14 @@ +mod author; + +use glib::prelude::*; + +fn main() { + let author = author::Author::new("John", "Doe"); + author.set_name("Jane"); + author.connect("awarded", true, |_author| { + println!("Author received a new award!"); + None + }); + + println!("Author: {} {}", author.name(), author.surname()); +}