|
| 1 | +use std::cell::Cell; |
| 2 | + |
| 3 | +use glib::subclass::InitializingObject; |
| 4 | +use gtk::glib; |
| 5 | +use gtk::prelude::*; |
| 6 | +use gtk::subclass::prelude::*; |
| 7 | +use gtk::CompositeTemplate; |
| 8 | + |
| 9 | +use crate::custom_button::CustomButton; |
| 10 | + |
| 11 | +// ANCHOR: object |
| 12 | +// Object holding the state |
| 13 | +#[derive(CompositeTemplate, Default)] |
| 14 | +#[template(resource = "/org/gtk-rs/example/window.ui")] |
| 15 | +pub struct Window { |
| 16 | + pub number: Cell<i32>, |
| 17 | +} |
| 18 | +// ANCHOR_END: object |
| 19 | + |
| 20 | +// ANCHOR: subclass |
| 21 | +// The central trait for subclassing a GObject |
| 22 | +#[glib::object_subclass] |
| 23 | +impl ObjectSubclass for Window { |
| 24 | + // `NAME` needs to match `class` attribute of template |
| 25 | + const NAME: &'static str = "MyGtkAppWindow"; |
| 26 | + type Type = super::Window; |
| 27 | + type ParentType = gtk::ApplicationWindow; |
| 28 | + |
| 29 | + fn class_init(klass: &mut Self::Class) { |
| 30 | + // Register `CustomButton` |
| 31 | + CustomButton::ensure_type(); |
| 32 | + |
| 33 | + klass.bind_template(); |
| 34 | + klass.bind_template_callbacks(); |
| 35 | + } |
| 36 | + |
| 37 | + fn instance_init(obj: &InitializingObject<Self>) { |
| 38 | + obj.init_template(); |
| 39 | + } |
| 40 | +} |
| 41 | +// ANCHOR_END: subclass |
| 42 | + |
| 43 | +// ANCHOR: template_callbacks |
| 44 | +#[gtk::template_callbacks] |
| 45 | +impl Window { |
| 46 | + #[template_callback] |
| 47 | + fn handle_button_clicked(&self, button: &CustomButton) { |
| 48 | + let number_increased = self.number.get() + 1; |
| 49 | + self.number.set(number_increased); |
| 50 | + button.set_label(&number_increased.to_string()) |
| 51 | + } |
| 52 | +} |
| 53 | +// ANCHOR_END: template_callbacks |
| 54 | + |
| 55 | +// Trait shared by all GObjects |
| 56 | +impl ObjectImpl for Window {} |
| 57 | + |
| 58 | +// Trait shared by all widgets |
| 59 | +impl WidgetImpl for Window {} |
| 60 | + |
| 61 | +// Trait shared by all windows |
| 62 | +impl WindowImpl for Window {} |
| 63 | + |
| 64 | +// Trait shared by all application |
| 65 | +impl ApplicationWindowImpl for Window {} |
0 commit comments