#[component]
Expand description
Macro that implements relm4::Component
or relm4::SimpleComponent
and generates the corresponding widgets struct.
§Attributes
To create public struct use #[component(pub)]
or #[component(visibility = pub)]
.
§Example
use relm4::prelude::*;
use gtk::prelude::*;
#[derive(Default)]
struct App {
counter: u8,
}
#[derive(Debug)]
enum Msg {
Increment,
Decrement,
}
#[relm4_macros::component(pub)]
impl SimpleComponent for App {
type Init = u8;
type Input = Msg;
type Output = ();
view! {
gtk::Window {
set_title: Some("Simple app"),
set_default_size: (300, 100),
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_margin_all: 5,
set_spacing: 5,
gtk::Button {
set_label: "Increment",
connect_clicked => Msg::Increment,
},
gtk::Button {
set_label: "Decrement",
connect_clicked[sender] => move |_| {
sender.input(Msg::Decrement);
},
},
gtk::Label {
set_margin_all: 5,
#[watch]
set_label: &format!("Counter: {}", model.counter),
}
},
}
}
fn init(
counter: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = Self { counter };
let widgets = view_output!();
ComponentParts { model, widgets }
}
fn update(&mut self, msg: Msg, _sender: ComponentSender<Self>) {
match msg {
Msg::Increment => {
self.counter = self.counter.wrapping_add(1);
}
Msg::Decrement => {
self.counter = self.counter.wrapping_sub(1);
}
}
}
}
§Notes on pre_view
Using return
in pre_view
will cause a compiler warning.
In general, you don’t want to use return
in pre_view
as it will
cause all following update functionality to be skipped.
ⓘ
struct App {}
#[relm4_macros::component]
impl SimpleComponent for App {
/* Code omitted */
fn pre_view() {
return;
}
}