2

I am looking for more info on how to include a GtkImage in an XML UI file, instead of creating them directly from code (In the documentation it only shows an example to create a GtkImage from C code and I want to do it from a *.UI resource).

What are the best practices for making icons or empty states with GtkImage in *.UI XML syntax? EDIT: Especially also in context of Flatpak.

Bastian
  • 620
  • 5
  • 14

1 Answers1

2

OK, here is my research so far.

This depends on whether you want to add an Icon from the existing icon set or add your own custom resource/image to your application. For GTK+3 we use the same class. For GTK+4, there is talk about having separate classes for icon and image. Below is instructions for GTK+ 3.

NB: In this example I added the GtkImage and GtkLabel inside a GtkBox container, as GtkWindow only allows one widget.


Adding a pre-defined Icon

See list of icons with the GTK+3 Icon Library.

Here is an example taken from Polari's source code on how to create a GTK Icon.

<object class="GtkImage">
  <property name="visible">True</property>
  <property name="icon-name">open-menu-symbolic</property>
  <property name="icon-size">1</property>
</object>

You can change the scale using either icon-size (4 is the default size we use for GTK+ applications) or pixel-size (should be a multiplier of 8, 16 or 24). Regardless of what you choose, both should work fine for Hi-DPI.


Adding a custom icon or image (PNG, SVG, JPG, etc)

This process requires two additional steps first, before we can write the XML code. 1. Put the image inside the src/ folder of your application source code.

  1. Register MyImage.png into the org.gnome.MyApplication.src.gresource.xml gressource file you have in src/.
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/org/gnome/MyApplication">
    <file>window.ui</file>
    <file>MyImage.png</file>
  </gresource>
</gresources>

3. Now we can add the GtkImage to our UI XML file.

<object class="GtkImage">
  <property name="visible">True</property>
  <property name="can_focus">False</property>
  <property name="resource">/org/gnome/MyApplication/MyImage.png</property>
  <property name="icon_size">1</property>
</object>

As can be seen, the path consists of the gresource prefix + the filename. By default, the image will be rendered 1:1. My own experiments have so far shown that you cannot use pixel-size or icon-size to control the size of a custom image file loaded like this.

custom image loaded from XML

Bastian
  • 620
  • 5
  • 14