DEV Community

Cover image for Refactoring GTK keyboard
Antonov Mike
Antonov Mike

Posted on

Refactoring GTK keyboard

In my first post on this site, I talked about creating a keyboard. I think it's time to rework the text a bit to make it easier to read. I made one more file named buttons.rs it contains buttons, entry and label implementations.

use gtk;
use gtk::{Button, Entry, Label};

pub fn create_button(label: &'static str) -> Button {
    let margin = 2;
    Button::builder()
        .label(label)
        .margin_start(margin)
        .margin_top(margin)
        .margin_end(margin)
        .margin_bottom(margin)
        .build()
}

pub fn create_entry() -> Entry {
    let margin = 2;
    Entry::builder()
        .margin_start(margin)
        .margin_top(margin)
        .margin_end(margin)
        .margin_bottom(margin)
        .build()
}

pub fn create_label(label: Option<&str>) -> Label {
    let margin = 2;
    let text: &str = label.unwrap_or("default string");
    Label::builder()
        .label(text)
        .margin_start(margin)
        .margin_top(margin)
        .margin_end(margin)
        .margin_bottom(margin)
        .build()
}
Enter fullscreen mode Exit fullscreen mode

We can’t add Option to .lebel() we have to convert Option into str label.unwrap_or("default string").
Add buttons.rs to main.rs file

use gtk::prelude::*;

mod gui;
mod buttons;
Enter fullscreen mode Exit fullscreen mode

Add functions as crates to gui.rs

use crate::buttons::create_label;
use crate::buttons::create_entry;
use crate::buttons::create_button;
Enter fullscreen mode Exit fullscreen mode

And declare buttons, labels and whatever you want following this example

let button_1 = create_button("Button 1");

let counter_label = create_label(Some("0.0"));

let label_time = create_label(None);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)