Search code examples
ciconsgtk3

How to use GResource to load an icon in Gtk3


This is my .gresource.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<gresources>
    <gresource prefix="/org/readaratus/decoder">
        <file alias="app_icon">icon192.png</file>
    </gresource>
</gresources>

I wrote this code to set the icon:

gtk_window_set_icon_from_file(GTK_WINDOW(ui.main_window),
                              "resource:///org/readaratus/decoder/app_icon",
                              NULL);

Which fails with the following warning:

Gtk-WARNING **: Error loading icon from file 'resource:///org/readaratus/decoder/app_icon':
    Failed to open file 'resource:///org/readaratus/decoder/app_icon': No such file or directory

But if I query the resources bundle, it reports an object with 3631 bytes:

gsize size;
if(g_resources_get_info("/org/readaratus/decoder/app_icon",
                        G_RESOURCE_LOOKUP_FLAGS_NONE,
                        &size, NULL, NULL))
{
    g_print("app_icon size: %ld\n", size);
}

What is wrong with my code and how do I load an icon from the resource?


Solution

  • GResource is not a file, but a binary resource bundled with your application/library. You should access it only with g_resource_*() methods or special methods which lookup data in resources, like gtk_image_new_from_resource, gtk_builder_new_from_resource, gdk_pixbuf_new_from_resource.

    In your case you should have loaded Gdkpixbuf and set it as icon separately.

    GdkPixbuf *pixbuf;
    pixbuf = gdk_pixbuf_new_from_resource ("/org/readaratus/decoder/app_icon", NULL);
    gtk_window_set_icon (window, pixbuf);
    

    Side note: if you have your icon hand-drawn in multiple sizes, use gtk_window_set_icon_list(). Then the best size will be used.