Skip to content

Instantly share code, notes, and snippets.

@zzeroo
Created January 24, 2019 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzeroo/9886edce46ca92f4c1805142d144410a to your computer and use it in GitHub Desktop.
Save zzeroo/9886edce46ca92f4c1805142d144410a to your computer and use it in GitHub Desktop.
extern crate gtk;
#[macro_use]
extern crate relm;
#[macro_use]
extern crate relm_derive;
use gtk::{
Button, ButtonExt, ContainerExt, Inhibit,
Orientation::{Horizontal, Vertical},
WidgetExt, Window, WindowType,
};
use relm::{Component, ContainerWidget, Relm, Update, Widget};
struct Model {
components: Vec<Component<MyWidget>>,
}
#[derive(Msg)]
enum Msg {
Quit,
Add,
}
struct Win {
model: Model,
widgets: Widgets,
}
struct Widgets {
hbox: gtk::Box,
window: Window,
}
struct MyWidget {
hbox: gtk::Box,
}
impl Update for MyWidget {
type Model = ();
type ModelParam = ();
type Msg = ();
fn model(_: &Relm<Self>, _: ()) -> Self::Model {
()
}
fn update(&mut self, event: Self::Msg) {
match event {
_ => (),
}
}
}
impl Widget for MyWidget {
type Root = gtk::Box;
fn root(&self) -> Self::Root {
self.hbox.clone()
}
fn view(_relm: &Relm<Self>, _model: Self::Model) -> Self {
let hbox = gtk::Box::new(Horizontal, 0);
let button = Button::new_with_label("MyWidget");
hbox.add(&button);
MyWidget { hbox }
}
}
impl Update for Win {
type Model = Model;
type ModelParam = ();
type Msg = Msg;
fn model(_: &Relm<Self>, _: ()) -> Self::Model {
Model { components: vec![] }
}
fn update(&mut self, event: Self::Msg) {
match event {
Msg::Add => {
// Adding the widget dosn't work
let widget = self.widgets.hbox.add_widget::<MyWidget>(());
self.model.components.push(widget);
println!("add ...");
}
Msg::Quit => gtk::main_quit(),
}
}
}
impl Widget for Win {
type Root = Window;
fn root(&self) -> Self::Root {
self.widgets.window.clone()
}
fn view(relm: &Relm<Self>, model: Self::Model) -> Self {
let window = Window::new(WindowType::Toplevel);
let hbox = gtk::Box::new(Vertical, 0);
let button = Button::new_with_label("ADD");
hbox.add(&button);
window.add(&hbox);
// // this works
// hbox.add_widget::<MyWidget>(());
// hbox.add_widget::<MyWidget>(());
window.show_all();
connect!(relm, button, connect_clicked(_), Msg::Add);
connect!(
relm,
window,
connect_delete_event(_, _),
return (Some(Msg::Quit), Inhibit(false))
);
Win {
model,
widgets: Widgets {
hbox: hbox,
window: window,
},
}
}
}
fn main() {
Win::run(()).expect("Win::run failed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment