Search code examples
gtkvala

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


I would like to use Gtk.Widget's ìnstall_style_property () on a widget I'm writing. In the docs, this method is declared as static, so I am wondering why valac still complains that I am calling it from a static method:

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

The error message:

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

If this does not work, what is the preferred pattern to install custom style properties to a custom widget in Gtk? Personally, I would prefer not to have to call an init () before using my widget, but as adding style properties is done per-class instead of per-instance, putting it into the constructor does not seem right, either.


Solution

  • install_style_property() is not static; it's actually a class method. valadoc.org is showing static for some reason; you'll probably have to report that as a bug (if it hasn't already).

    class methods operate on a class itself. GObject classes have shared metadata, and these methods modify that metadata. Such metadata should only be modified when the class is first initialized; therefore, the methods should only be called within that class's GObjectClass.class_init() method. In Vala, this is the static construct method:

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