gtk-rs / gtk3-rs

Rust bindings for GTK 3
https://gtk-rs.org
MIT License
507 stars 90 forks source link

[HELP] How do I get the width and height of the current screen? #848

Closed ghost closed 11 months ago

ghost commented 1 year ago

I'm trying to build a status bar for my Arch system, I trawled through the API docs and couldn't find anything that explains how to get the width of the entire screen and make that the app's width. (Bit frustrated, I find the project great but I'd appreciate some guidance on this.) Also, styling-wise can I set things like colors and fonts without CSS or do I have to use CSS?

ski0090 commented 11 months ago

try this

fn build_ui(application: &gtk::Application) {
    let window = gtk::ApplicationWindow::new(application);

    window.set_title("First GTK+ Program");
    window.set_border_width(10);
    window.set_position(gtk::WindowPosition::Center);

    let label = if let Some((w, h)) = rect_from_display_rate(0.8) {
        window.set_width_request(w);
        window.set_height_request(h);
        gtk::Label::new(Some(&format!("{w} x {h}")))
    } else {
        gtk::Label::new(Some(&format!("no monitor")))
    };

    window.add(&label);

    window.show_all();
}

fn rect_from_display_rate(rate: f64) -> Option<(i32, i32)> {
    let display = gdk::Display::default()?;
    let monitor = display.monitor(0)?;
    let rect = monitor.workarea();
    let w = (rect.width() as f64 * rate) as i32;
    let h = (rect.height() as f64 * rate) as i32;
    Some((w, h))
}
ghost commented 11 months ago

Hi @ski0090!! Thank you for your reply and the code you posted. I'm going to try this as soon as I get back home. I was also wondering how I could make the window a direct child of the root window? Because I'm making something like Polybar or at least I wanted to. Because I want it to be static and take up a certain amount of space on the screen. Basically I want to make a system panel that stays at the top of the screen using GTK.

GuillaumeGomez commented 11 months ago

This is not a place to get help for using this crate. For that, please use the matrix channel (#rust:gnome.org).