Skip to content

Instantly share code, notes, and snippets.

@ikapper
Created May 14, 2023 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikapper/fede8359a265b21f93a8848020049e4a to your computer and use it in GitHub Desktop.
Save ikapper/fede8359a265b21f93a8848020049e4a to your computer and use it in GitHub Desktop.
gtk_rs_tutorial
/// references between widgets example
///
/// ref: https://gtk-rs.org/gtk4-rs/stable/latest/book/g_object_memory_management.html
use std::cell::Cell;
use std::rc::Rc;
use gtk::prelude::*;
use gtk::{
glib::{self, clone},
Application, ApplicationWindow, Button, Label,
};
const APP_ID: &str = "com.example.firstapp";
fn main() -> glib::ExitCode {
let app = Application::builder().application_id(APP_ID).build();
// Connect build_ui to "activate" signal of app
app.connect_activate(build_ui);
app.run()
}
fn build_ui(app: &Application) {
let inc_button = Button::builder()
.label("increase")
.margin_top(12)
.margin_bottom(12)
.margin_start(12)
.margin_end(12)
.build();
let dec_button = Button::builder()
.label("decrease")
.margin_top(12)
.margin_bottom(12)
.margin_start(12)
.margin_end(12)
.build();
let number = Rc::new(Cell::new(0));
let label = Label::builder()
.label(number.get().to_string())
.margin_top(12)
.margin_bottom(12)
.margin_start(12)
.margin_end(12)
.build();
inc_button.connect_clicked(clone!(@weak number as n, @weak label => move |_| {
n.set(n.get()+1);
label.set_label(&n.get().to_string());
}));
// `number` keeps alive without `@weak number` or with `@strong number`
dec_button.connect_clicked(clone!(@weak label => move |_| {
number.set(number.get()-1);
label.set_label(&number.get().to_string());
}));
// `gtk_box` holds all three widgets above
let gtk_box = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.build();
gtk_box.append(&dec_button);
gtk_box.append(&label);
gtk_box.append(&inc_button);
// create a window and set the title
let window = ApplicationWindow::builder()
.application(app)
.title("my-gtk-app")
.child(&gtk_box)
.build();
// Present window
window.present();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment