user-interfacerustfltk

How can i show changes on a grid in fltk-rs?


I am making a basic application in fltk-rs that uses a fltk-grid. I want to update the widgets of that grid and then show the changes made.

This is my code:

main.rs

use fltk::{app, prelude::*, window::Window, button};
use std::{cell::RefCell, rc::Rc};

mod grid;
fn main() {
    let number = Rc::new(RefCell::new(0));
    
    let app = app::App::default();
    let mut wind = Window::default()
        .with_size(900, 500)
        .center_screen()
        .with_label("Test app.");

    // Main grid
    let mut main_grid = grid::create();

    // Button
    let mut stats_button = button::Button::default().with_label("Update");
    main_grid.set_widget(&mut stats_button, 4, 4);

    main_grid.end();

    stats_button.set_callback(move |_| {
        *number.borrow_mut() += 1;
        grid::update(number.clone(), &mut main_grid);
        app::redraw();
    });

    wind.end();
    wind.show();

    app.run().unwrap();
    
}

grid.rs

use fltk::{frame, prelude::*};
use fltk_grid::Grid;
use std::{rc::Rc, cell::RefCell};

pub fn create() -> Grid {
    let mut grid = Grid::default_fill();
    grid.show_grid(false);
    grid.set_layout(9, 9);
    grid
}

pub fn update(data: Rc<RefCell<u32>>, grid: &mut Grid) {
    // Updates the grid with a new label
    let label =  format!("Number = {}.",data.borrow());
    let mut lable_message = frame::Frame::default().with_label(&label);

    grid.set_widget(&mut lable_message, 3, 4);
}

Cargo.toml

[package]
name = "trash"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
fltk = "^1.4"
fltk-grid = "0.4"

Pressing the button 'Update' does not show the frame widget assigned to the grid. I tried showing, hiding and redrawing the grid, the window and the app.


Solution

  • You would need to add the label_message frame to the grid, as it stands now, it's not a child of the grid.

    // in update
            grid.add(&lable_message);
            grid.set_widget(&mut lable_message, 3, 4);
    

    You also shouldn't need the call to app::redraw().