Raccoondude
Raccoondude

Reputation: 21

Getting input from a GTK::Entry in rs-GTK

First of all, im very new to rust and COMPLETELY new at GTK

I would like to print the contents of "Input" when pressing the button

How do I do this?

Code:

extern crate gtk;
extern crate gio;

use gtk::prelude::*;
use gio::prelude::*;

use gtk::{Application, ApplicationWindow, Button};

fn main() {
    let application = Application::new(
        Some("com.github.gtk-rs.examples.basic"),
        Default::default(),
        ).expect("Failed :(");
    application.connect_activate(|app| {
        let window = ApplicationWindow::new(app);
        window.set_title("Title");
        window.set_default_size(350, 70);
        let win_title = gtk::Label::new(None);
        win_title.set_markup("Cool title here");
        let Input = gtk::Entry::new();
        let row = gtk::Box::new(gtk::Orientation::Vertical, 5);
        row.add(&win_title);
        row.add(&Input);
        let button = Button::with_label("Click me!");
        button.connect_clicked(|_| {
            println!("This should be the contents of Input");
        });
        row.add(&button);
        window.add(&row);
        window.show_all();
    });
    application.run(&[]);
}```

Upvotes: 2

Views: 768

Answers (1)

frankenapps
frankenapps

Reputation: 8241

You are almost there.

You can get the text from the Entry using input.get_text(). Then you also need to use the move keyword to allow your closure to take ownership of the entry.

Please note, that I changed the variable name Input to lowercase (snake_case), because this is the suggested style in Rust.

Here is the updated example based on your code:

use gtk::prelude::*;
use gio::prelude::*;

use gtk::{Application, ApplicationWindow, Button};

fn main() {
    let application = Application::new(
        Some("com.github.gtk-rs.examples.basic"),
        Default::default(),
        ).expect("Failed :(");
    application.connect_activate(|app| {
        let window = ApplicationWindow::new(app);
        window.set_title("Title");
        window.set_default_size(350, 70);
        let win_title = gtk::Label::new(None);
        win_title.set_markup("Cool title here");
        let input = gtk::Entry::new();
        let row = gtk::Box::new(gtk::Orientation::Vertical, 5);
        row.add(&win_title);
        row.add(&input);
        let button = Button::with_label("Click me!");
        button.connect_clicked(move |_| {
            println!("{}", input.get_text());
        });
        row.add(&button);
        window.add(&row);
        window.show_all();
    });
    application.run(&[]);
}

Upvotes: 2

Related Questions