I am trying to get the keys that a user is typing in without having an editable Entry or TextView. I saw an example with window.connect on an older version. I tried getting the “key_press” via the connect_closure, but keep getting an error that ‘key_press’ is not found on GtkApplicationWindow.
What is the best way to achieve this goal? What am I doing wrong?
Help will be highly appreciated.
Thanks, Alex
use gdk::prelude::{ApplicationExt, ApplicationExtManual, ObjectExt};
use glib::ToValue;
use gtk::glib;
use gtk::traits::{GtkWindowExt, WidgetExt};
static APP_ID: &str = "org.gtkrs.keylistener";
fn build_ui(application: >k::Application) {
let window = gtk::ApplicationWindow::builder()
.application(application)
.title("Key Listener Experiment")
.build();
let gclosure = glib::RustClosure::new(|values| {
println!("values: {:#?}", values);
// Values is an Event object?
let event_type = &values[1].get::<gdk::EventType>().unwrap();
let raw_event = &values[1].get::<gdk::Event>().unwrap();
println!("event_type: {:#?}", event_type);
println!("raw_event: {:#?}", raw_event);
println!("raw_event_keycode(): {:#?}", raw_event.keycode());
println!("raw_event_keyval(): {:#?}", raw_event.keyval());
Some("Hello".to_value())
});
window.connect_closure("key_press", false, gclosure);
let vbox = gtk::Box::builder()
.spacing(5)
.orientation(gtk::Orientation::Vertical)
.build();
window.set_child(Some(&vbox));
window.show();
}
fn main() {
let app = gtk::Application::builder().application_id(APP_ID).build();
app.connect_activate(build_ui);
app.run();
}
// Create an EventController
let eventctl = gtk::EventControllerKey::new();
eventctl.connect_key_pressed( ); // What are the arguments of the function ... ?
// connect_key_pressed
window.add_controller(eventctl);
I can’t understand what arguments to pass to eventcontroller.connect_key_pressed? I see that it expects a Key, u32, and a gdk::ModifierType. But I can’t seem to get past this. And I can’t find any examples anywhere. Help would be appreciated.
The docs do provide the names and descriptions of the arguments, although they are a translation from the C docs so it is not the most understandable: EventControllerKey in gtk4 - Rust
Sorry about that, not sure how we could improve that for gtk-rs, because Rust does not support named arguments in a Fn bound. But if you write your handler you could put the names in:
You can see there keyval and keycode correspond to the usage in your sample code, and the last argument is the modifiers (shift/ctrl/alt/etc) held when the key was pressed. The names are also in those generated trampoline functions if you prefer to look at the implementation to grab them.