Valac 不允许我从静态方法中 "install_style_property"

Valac won't let me "install_style_property" from a static method

我想在我正在编写的小部件上使用 Gtk.Widget 的 ìnstall_style_property ()。在文档中,这个方法被声明为 static,所以我想知道为什么 valac 仍然抱怨我是从静态方法调用它的:

public class MyClass : Gtk.Widget {

    public static void init () {
        ParamSpecDouble _the_property = new ParamSpecDouble
        (
            "dummy", "dummy", "dummy,
            0, double.MAX, 0,
            ParamFlags.READWRITE | ParamFlags.STATIC_STRINGS
        );
        install_style_property (_the_property);
    }
}

void main (string? argv) {
    Gtk.init (ref argv);
    MyClass.init ();
}

错误信息:

test.vala:11.9-11.46: error: Access to instance member `Gtk.Widget.install_style_property' denied

如果这不起作用,将自定义样式属性安装到 Gtk 中的自定义小部件的首选模式是什么?就个人而言,我宁愿在使用我的小部件之前不必调用 init (),但是由于添加样式属性是按 class 而不是按实例完成的,因此将其放入构造函数似乎不正确, 要么.

install_style_property() 不是 static;它实际上是一个 class 方法。 valadoc.org 出于某种原因显示 static;您可能必须将其报告为错误(如果尚未报告)。

class 方法在 class 本身 上运行 。 GObject classes 具有共享元数据,并且这些方法修改该元数据。此类元数据应仅在首次初始化 class 时修改;因此,只能在 class 的 GObjectClass.class_init() 方法中调用这些方法。在 Vala 中,这是 static construct 方法:

public class MyClass : Gtk.Widget {

    static construct {
        ParamSpecDouble _the_property = new ParamSpecDouble
        (
            "dummy", "dummy", "dummy,
            0, double.MAX, 0,
            ParamFlags.READWRITE | ParamFlags.STATIC_STRINGS
        );
        install_style_property (_the_property);
    }
}