user4209617
user4209617

Reputation:

"Invalid object type" When using a custom widget in Gtk.Builder ui file

Consider the following:

class MyCustomWidget : Gtk.Widget {
    public MyCustomWidget () {
        Object ();
    }
}

void main (string args[]) {
    string ui_string = """
    <?xml version="1.0" encoding="UTF-8"?>
    <interface>
        <object class="MyCustomWidget">
        </object>
    </interface>
    """;

    Gtk.init (ref args);    
    Gtk.Builder builder = new Gtk.Builder.from_string (ui_string, ui_string.length);
}

I am creating a custom Widget derived from Gtk.Widget. When using this widget with Gtk.Builder, I get the following error and the program crashes:

(bla:22282): Gtk-ERROR **: failed to add UI: .:4:1 Invalid object type 'MyCustomWidget'

Upvotes: 4

Views: 1968

Answers (1)

user4209617
user4209617

Reputation:

This happens because the type MyCustomWidget is not yet known to Gtk.Builder. This is why custom widgets should be instantiated at least once before being used with Gtk.Builder. This instance can then be thrown away.

void main (string args[]) {
    string ui_string = """
    <?xml version="1.0" encoding="UTF-8"?>
    <interface>
        <object class="MyCustomWidget">
        </object>
    </interface>
    """;

    Gtk.init (ref args);
    // create a throw-away instance of MyCustomWidget
    var tmp = new MyCustomWidget ();   
    Gtk.Builder builder = new Gtk.Builder.from_string (ui_string, ui_string.length);
}

Upvotes: 2

Related Questions