Package: gtk

Function gtk:widget-init-template

Lambda List

gtk:widget-init-template (widget)

Arguments

widget -- a gtk:widget object

Details

Creates and initializes child widgets defined in templates. Any class that uses the gtk:widget-class-set-template function to assign itself a template must call this function in its instance initializer. The g:object-instance-init method is a good place to do so.

It is important to call this function in the instance initializer of a gtk:widget subclass. One reason is that generally derived widgets will assume that parent class composite widgets have been created in their instance initializers. Another reason is that when calling the g:object-new function on a widget with composite templates, it is important to build the composite widgets before the construct properties are set. Properties passed to the g:object-new function should take precedence over properties set in the private template XML.

Examples

This is a complete example of how to use templates. It is part of the GTK Demo, that comes with the cl-cffi-gtk4 library.
;; Subclass from GtkApplicationWindow
(gobject:define-gobject-subclass "MyAppWindow" my-app-window
  (:superclass gtk:application-window
   :export t
   :interfaces nil)
  nil)

;; Set template and bindings during class initialization (defmethod gobject:object-class-init :after ((subclass (eql (find-class 'my-app-window))) class data) (declare (ignorable subclass class data)) ;; Load template from file, this is a Lisp extension (let ((path (glib-sys:sys-path "resource/widget-template.ui"))) (gtk:widget-class-set-template-from-file "MyAppWindow" path)) ;; Set builder scope (gtk:widget-class-set-template-scope "MyAppWindow" (make-instance 'gtk:builder-cl-scope)) ;; Bind objects from the template (gtk:widget-class-bind-template-child "MyAppWindow" "button1") (gtk:widget-class-bind-template-child "MyAppWindow" "button2") (gtk:widget-class-bind-template-child "MyAppWindow" "button3") (gtk:widget-class-bind-template-child "MyAppWindow" "button4"))

;; Init usage of template in instance initialization (defmethod gobject:object-instance-init :after ((subclass (eql (find-class 'my-app-window))) instance data) (declare (ignorable subclass data)) (gtk:widget-init-template instance))

;; Signal handlers for the buttons in the template (defun button-clicked (button) (format t " Button is clicked: ~a~%" button)) (defun button1-clicked (button) (format t " Button 1 is clicked: ~a~%" button)) (defun button2-clicked (button) (format t " Button 2 is clicked: ~a~%" button))

(defun do-widget-template (&optional application) (let* ((window (make-instance 'my-app-window :application application :title "Application Window" :show-menubar t))) ;; Present the application window (gtk:window-present window)))
 

See also

2025-12-07