How to force a gtk-rs widget to reread an updated value?

I am trying to update the 'counter' in a label 'label_info' through a button 'button_inc'. Athough the println! 'number_inc.get()' does show the correct, increased, number, the label is not updated. What am I doing wrong?

Help would be appreciated.

Thanks in advance.
Alex

use gtk::glib;
use gtk::prelude::*;
use gtk::Application;
use std::cell::Cell;
use std::rc::Rc;

static APP_ID: &str = "org.gtkrs-experiment";

fn main() -> glib::ExitCode {
    let app = gtk::Application::builder().application_id(APP_ID).build();
    app.connect_activate(build_ui);
    app.run()
}

fn build_ui(application: &Application) {
    let number = Rc::new(Cell::new(0));

    let number_inc = number.clone();
    let button_inc = gtk::Button::builder().label("Plus 1").build();

    button_inc.connect_clicked(move |_| {
        number_inc.set(number_inc.get() + 1);
        println!("The number_inc: {}", number_inc.get());
    });

    let label_info = gtk::Label::builder()
        .label(format!("The number is {}", number.get()))
        .build();

    let vbox = gtk::Box::builder()
        .orientation(gtk::Orientation::Vertical)
        .build();

    vbox.append(&label_info);
    vbox.append(&button_inc);

    let window = gtk::ApplicationWindow::builder()
        .application(application)
        .title("GTK Counter Experiment")
        .child(&vbox)
        .build();

    window.present()
}

The documentation for Cell::get explicitly states that it copies the value, which means that it can't update (if the provided function runs once, if it runs multiple times the cell will be re-initialized).

I think you somehow need to pass a function or a GTK variable, but I am unsure as I have never used this framework myself.

You need to update the label_info's text in the button_inc.connect_clicked closure. You should be able to do that with the LabelExt::set_text method. You'll also probably need to place the connect_clicked call in between the two vbox.append calls or clone the label_info before calling it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.