&引用;无效的对象类型";在Gtk.Builder ui文件中使用自定义小部件时

&引用;无效的对象类型";在Gtk.Builder ui文件中使用自定义小部件时,gtk,gtk3,vala,Gtk,Gtk3,Vala,考虑以下几点: class MyCustomWidget : Gtk.Widget { public MyCustomWidget () { Object (); } } void main (string args[]) { string ui_string = """ <?xml version="1.0" encoding="UTF-8"?> <interface> <object cl

考虑以下几点:

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);
}

这是因为Gtk.Builder还不知道MyCustomWidget类型。这就是为什么在与Gtk.Builder一起使用之前,自定义小部件应该至少实例化一次。然后就可以扔掉这个实例

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);
}
void main(字符串参数[]){
字符串ui_string=“”
""";
Gtk.init(参考参数);
//创建MyCustomWidget的一次性实例
var tmp=newmycustomwidget();
Gtk.Builder=new Gtk.Builder.from_string(ui_string,ui_string.length);
}

Vala是否有办法注册类而不创建新对象,相当于调用C中的
classname\u get\u type()
函数?物体会立即被摧毁吗?(我有一段时间没有使用Vala…)可能的重复:@JoséFonte no,因为答案是关于在glade UI编辑器中使用自定义小部件,而不是在实际代码中。我不同意创建虚拟实例是正确的解决方案。它不应该被需要,甚至可能在某些语言中被优化,除非你有创意@andlabs:GtkBuilder
.ui
文件中的
type func
属性应该可以工作。。。至少,我觉得自己好像看见一只虫子从身边经过,就能把它修好。此外,根据一位经验丰富的GNOME开发人员的说法,如果
typefunc
不可用,那么答案是在Vala代码中调用
typeof(Gtk.Whatever)
:下划线d我可以确认添加到UI定义文件中的
typefunc=“mycustomwidget\u get\u type”
正确地解决了同样的问题。
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);
}