Skip to content

Commit e93e899

Browse files
authored
Merge pull request #1145 from ranfdev/master
Add object_subclass example
2 parents 03bce03 + bddbc65 commit e93e899

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

examples/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,7 @@ path = "gio_task/main.rs"
4444
[[bin]]
4545
name = "gio_cancellable_future"
4646
path = "gio_cancellable_future/main.rs"
47+
48+
[[bin]]
49+
name = "object_subclass"
50+
path = "object_subclass/main.rs"

examples/object_subclass/author.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// You can copy/paste this file every time you need a simple GObject
2+
// to hold some data
3+
4+
use glib::once_cell::sync::Lazy;
5+
use glib::prelude::*;
6+
use glib::subclass::prelude::*;
7+
use glib::subclass::Signal;
8+
use glib::Properties;
9+
use std::cell::RefCell;
10+
11+
mod imp {
12+
use super::*;
13+
14+
#[derive(Properties, Default)]
15+
#[properties(wrapper_type = super::Author)]
16+
pub struct Author {
17+
#[property(get, set)]
18+
name: RefCell<String>,
19+
#[property(get, set)]
20+
surname: RefCell<String>,
21+
}
22+
23+
#[glib::derived_properties]
24+
impl ObjectImpl for Author {
25+
fn signals() -> &'static [Signal] {
26+
static SIGNALS: Lazy<Vec<Signal>> =
27+
Lazy::new(|| vec![Signal::builder("awarded").build()]);
28+
SIGNALS.as_ref()
29+
}
30+
}
31+
32+
#[glib::object_subclass]
33+
impl ObjectSubclass for Author {
34+
const NAME: &'static str = "Author";
35+
type Type = super::Author;
36+
}
37+
}
38+
39+
glib::wrapper! {
40+
pub struct Author(ObjectSubclass<imp::Author>);
41+
}
42+
impl Author {
43+
pub fn new(name: &str, surname: &str) -> Self {
44+
glib::Object::builder()
45+
.property("name", name)
46+
.property("surname", surname)
47+
.build()
48+
}
49+
}

examples/object_subclass/main.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
mod author;
2+
3+
use glib::prelude::*;
4+
5+
fn main() {
6+
let author = author::Author::new("John", "Doe");
7+
author.set_name("Jane");
8+
author.connect("awarded", true, |_author| {
9+
println!("Author received a new award!");
10+
None
11+
});
12+
13+
println!("Author: {} {}", author.name(), author.surname());
14+
}

0 commit comments

Comments
 (0)