Search code examples
rustgtkrust-cargogtk4

Why can't I use clone!() in gtk4 for Rust?


I've just installed gtk4 over gtk for Rust and wrote a hello world program to test if it works. I want to use the clone macro to pass a weak reference for my button but, its not recognising the clone in gtk4::glib and says I have to use gtk::glib and glib::clone but does not work because clone isn't in gtk4.

The error I get in my editor is:

   glib needs to be in scope, so unless it's one of the direct crate 
   dependencies, you need to import it because clone! is using it. 
   For example: use gtk::glib;

Here is my code:

use glib::clone;
use gtk::prelude::*;
use gtk::{glib, Application};
use gtk4 as gtk;

fn main() {
    let app = Application::builder().application_id("hello-workd").build();

    app.connect_activate(build_ui);
    app.run();
}

fn build_ui(app: &gtk4::Application) {
    let button = gtk::Button::with_label("Hello World!");

    //error here
    button.connect_clicked(clone!(@weak button => move |_| {
        button.set_label("Hello to you!")
    }));

    let window = gtk::ApplicationWindow::builder()
        .application(app)
        .title("Hello World App")
        .child(&button)
        .build();

    window.present();
}

The program compiles and runs but I get the following warnings in my terminal:

GLib-GIO-CRITICAL **: 
g_application_set_application_id: assertion 'application_id == 
NULL || g_application_id_is_valid (application_id)' failed

and

Gtk-WARNING **: Unknown key gtk-modules in 
/home/../.config/gtk-4.0/settings.ini

Is there a way I can use gtk4 instead of gtk?


Solution

  • The in editor message is only a notice (which I also cannot reproduce), there is nothing to be done about that. The real error is that "hello-workd" isn't a valid application id:

    • Application identifiers are composed of 1 or more elements separated by a period (.) character. All elements must contain at least one character.
    • Each element must only contain the ASCII characters [A-Z][a-z][0-9]_-, with - discouraged in new application identifiers. Each element must not begin with a digit.
    • Application identifiers must contain at least one . (period) character (and thus at least two elements).
    • Application identifiers must not begin with a . (period) character.
    • Application identifiers must not exceed 255 characters.

    Specifically it does not consist of two elements, try "hello.workd" instead.