Vala and Custom Widgets

There is a case when you wish to use a custom widget, when you use the same set of widgets to handle data. When you create a Gtk.ListBoxRow you have to attach to it a Gtk.Widget, in that case, should be easiest if you just do

var w = new MyWidget ();
w.data = data;

Second line, sets your data to the widget’s data property, so the class initialize the UI with the provided data.

In other case, you have a Widget you can re-use in different parts of the UI, maybe showed up in a popup window. This is the process you can use to create such a widget.

Create a Widget in Glade

Yes, use Glade to create a template UI file for your new widget, for the example, lets start with this simple user interface:

Key aspects is set Composite in order to define it as a Widget class definition, make sure you set Class Name to the same C name of your class, that is include the namespace, in our example the namespace is My so the widget class name is set to MyWidget.

Define your Class

Now, make sure you setup the Widget class to  use the UI  you will use. Name all entries and buttons, or any other UI elements you plan to use in your custom widgets at UI design time; use that name in your source code as follows:

Gtk.Entry evalue1 will be linked to your entry with the Id evalue1 so you can use it as any other variable. To link, use [GtkChild] annotation and [GtkTemplate]  one for the class, setting the attribute uiwith the name of the UI file in the resources file; in this case defined as:

UI file linked to the widget class, should be embedded in your program as a GLib resource. Set prefix to the path for the resource resolution, useful to classify different resources.

If you misspell the UI file or the ChildWidge‘s name you’ll get the following kind of errors:

Make it Interactive

Lets take a view at the bmultiply variable, linked to a Gtk.Button with the id set to, and how above code connect to its clicked signal to perform an operation and set the result to the text of the Gtk.Entry with the Id eresult  just accessing the variables defined as private in the My.Widget.

Base for your Class

Above widget, is a subclass of  Gtk.Box so you should make sure your top level widget in the UI definition is of the same type, as you can see at the Glade screenshot. You can take any other base class, depending on the functionality you want to start from.

Author: despinosa

Linux and GNOME user, full time, since 2001. Actual maintainer of GXml and contributor to other projects mainly on GObject Introspection support.

Leave a Reply

Your email address will not be published. Required fields are marked *