combo_box/
combo_box.rs

1#![allow(deprecated)]
2
3use gtk::prelude::*;
4use relm4::{
5    Component, ComponentController, ComponentParts, ComponentSender, Controller, RelmApp,
6    SimpleComponent, gtk,
7};
8use relm4_components::simple_combo_box::SimpleComboBox;
9
10type ComboContent = &'static str;
11
12const GREETINGS: &[&str] = &["Hello!", "Hallo!", "Salut!", "Siema!", "привет!", "你好!"];
13
14#[derive(Debug)]
15enum AppMsg {
16    ComboChanged(usize),
17}
18
19struct App {
20    combo: Controller<SimpleComboBox<ComboContent>>,
21    idx: usize,
22}
23
24impl App {
25    fn lang(&self) -> &str {
26        // you can also use self.combo.model().variants[self.idx]
27        self.combo
28            .model()
29            .get_active_elem()
30            .expect("combo box should have an active element")
31    }
32
33    fn greeting(&self) -> &str {
34        GREETINGS[self.idx]
35    }
36
37    fn label(&self) -> String {
38        format!("Greeting in {}: {}", self.lang(), self.greeting())
39    }
40}
41
42#[relm4::component]
43impl SimpleComponent for App {
44    type Init = ();
45    type Input = AppMsg;
46    type Output = ();
47
48    view! {
49        gtk::ApplicationWindow {
50            set_default_size: (300, 300),
51
52            gtk::Box {
53                set_orientation: gtk::Orientation::Vertical,
54
55                #[local_ref]
56                combo -> gtk::ComboBoxText {},
57
58                gtk::Label {
59                    #[watch]
60                    set_label: &model.label(),
61                },
62            }
63        }
64    }
65
66    fn update(&mut self, msg: Self::Input, _: ComponentSender<Self>) {
67        match msg {
68            AppMsg::ComboChanged(idx) => self.idx = idx,
69        }
70    }
71
72    fn init(
73        _: Self::Init,
74        root: Self::Root,
75        sender: ComponentSender<Self>,
76    ) -> ComponentParts<Self> {
77        let default_idx = 0;
78
79        let langs = vec![
80            "English", "German", "French", "Polish", "Russian", "Chinese",
81        ];
82
83        let combo = SimpleComboBox::builder()
84            .launch(SimpleComboBox {
85                variants: langs,
86                active_index: Some(default_idx),
87            })
88            .forward(sender.input_sender(), AppMsg::ComboChanged);
89
90        let model = App {
91            combo,
92            idx: default_idx,
93        };
94
95        let combo = model.combo.widget();
96        let widgets = view_output!();
97
98        ComponentParts { model, widgets }
99    }
100}
101
102fn main() {
103    let app = RelmApp::new("relm4.example.combo_box");
104    app.run::<App>(());
105}