How can I change the font size of a Gtk.Label in vala?

痞子三分冷 提交于 2019-12-01 00:34:30

You could try with css, I think lately this is the preferred way. Give your label a class, then load a css. If you are going to change the font size of a label, I bet you are also going to customize other things so the css may be useful for you.

Thanks lethalman and nemequ.

I think it might help someone so here is a little example of how to use css with Vala.

using Gtk;

public class StyleApp1 : Gtk.Window
{
    public StyleApp1() 
    {

        this.title = "Style app example";
        this.set_border_width (10);
        this.set_position (Gtk.WindowPosition.CENTER);

        this.set_default_size (350, 200);
        this.destroy.connect (Gtk.main_quit);

        var screen = this.get_screen ();
        var css_provider = new Gtk.CssProvider();

        string path = "styleapp1.css";

        // test if the css file exist
        if (FileUtils.test (path, FileTest.EXISTS))
        {
            try {
                css_provider.load_from_path(path);
                Gtk.StyleContext.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER);
            } catch (Error e) {
                error ("Cannot load CSS stylesheet: %s", e.message);
            }
        }

        var box = new Gtk.Box (Gtk.Orientation.VERTICAL, 10);
        this.add (box);

        var label = new Gtk.Label ("Thank you");
        box.add (label);

        var label2 = new Gtk.Label ("Stackoverflow");
        label2.get_style_context().add_class("my_class");
        box.add (label2);
    }
}

static int main(string[] args) {
    Gtk.init(ref args);

    StyleApp1 win = new StyleApp1();
    win.show_all();

    Gtk.main();
    return 0;
}

and the styleapp1.css file :

GtkWindow {
    font-size: 17px;
}

.my_class {
    color: pink;
}

NB : if you use add_provider instead of add_provider_for_screen. You have to use add_provider for every widget that you want to customize.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!