Chapter 28. Custom Widgets

Table of Contents

gtkmm makes it very easy to derive new widgets by inheriting from an existing widget class, either by deriving from a container and adding child widgets, or by deriving from a single-item widget, and changing its behavior. But you might occasionally find that no suitable starting point already exists. In this case, you can implement a widget from scratch.

Custom Containers

When deriving a custom container widget directly from Gtk::Widget, you should override the following virtual methods:

  • get_request_mode_vfunc(): Return what Gtk::SizeRequestMode is preferred by the container.

  • measure_vfunc(): Calculate the minimum and natural width or height of the container.

  • size_allocate_vfunc(): Position the child widgets, given the height and width that the container has actually been given.

The get_request_mode_vfunc(), measure_vfunc(), and size_allocate_vfunc() virtual methods control the layout of the child widgets. For instance, if your container has 2 child widgets, with one below the other, your get_request_mode_vfunc() might request height-for-width layout. Then your measure_vfunc() might report the maximum of the widths of the child widgets when asked to report width, and it might report the sum of their heights when asked to report height. If you want padding between the child widgets then you would add that to the width and height too. Your widget's container will use this result to ensure that your widget gets enough space, and not less. By examining each widget's parent, and its parent, this logic will eventually decide the size of the top-level window.

You are not guaranteed to get the Gtk::SizeRequestMode that you request. Therefore measure_vfunc() must return sensible values for all reasonable values of its input parameters. For a description of measure_vfunc()'s parameters see also the description of Gtk::Widget::measure(), which may be better documented than measure_vfunc().

size_allocate_vfunc() receives the actual height and width that the parent container has decided to give to your widget. This might be more than the minimum, or even more than the natural size, for instance if the top-level window has been expanded. You might choose to ignore the extra space and leave a blank area, or you might choose to expand your child widgets to fill the space, or you might choose to expand the padding between your widgets. It's your container, so you decide.

Your container must unparent its children before the underlying C object (a gtkmm__GtkWidget) is finalized. If your container is used as a managed widget, it shall unparent its children in a Gtk::Widget::signal_destroy() handler (available since gtkmm 4.8). If your container is not managed, that signal handler is not called. Instead the children shall be unparented in the C++ destructor. If you want your container to be useful both ways, unparent the children both in the destructor and in a signal handler. See the example code.

Example

This example implements a container with child widgets, one above the other. Of course, in this case it would be far simpler just to use a vertical Gtk::Box or Gtk::Grid.

Figure 28.1. Custom Container

Custom Container

Source Code

File: examplewindow.h (For use with gtkmm 4)

#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include <gtkmm.h>
#include "mycontainer.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  ~ExampleWindow() override;

protected:
  //Signal handlers:
  void on_button_quit();

  //Child widgets:
  Gtk::Box m_VBox;
  MyContainer m_MyContainer;
  Gtk::Button m_Button_Child;
  Gtk::Label m_Label_Child;
  Gtk::Box m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H

File: mycontainer.h (For use with gtkmm 4)

#ifndef GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
#define GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H

#include <gtkmm/widget.h>
#include <gtkmm/version.h>

#define HAS_SIGNAL_DESTROY GTKMM_CHECK_VERSION(4,7,1)

class MyContainer : public Gtk::Widget
{
public:
  MyContainer();
  ~MyContainer() override;

  void append(Gtk::Widget& child);
  void prepend(Gtk::Widget& child);
  void remove(Gtk::Widget& child);

protected:
  int get_nvis_children() const;

  //Overrides:
  Gtk::SizeRequestMode get_request_mode_vfunc() const override;
  void measure_vfunc(Gtk::Orientation orientation, int for_size, int& minimum, int& natural,
    int& minimum_baseline, int& natural_baseline) const override;
  void size_allocate_vfunc(int width, int height, int baseline) override;

#if HAS_SIGNAL_DESTROY
  // Signal handler:
  void on_container_destroy();
#endif
};

#endif //GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H

File: examplewindow.cc (For use with gtkmm 4)

#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::Orientation::VERTICAL),
  m_Button_Child("Child button"),
  m_Label_Child("Child label", Gtk::Align::END, Gtk::Align::CENTER),
  m_Button_Quit("Quit")
{
  set_title("Custom Container example");
  set_default_size(400, 200);

  m_VBox.set_margin(6);
  set_child(m_VBox);

  //Add the child widgets to the custom container:
  m_MyContainer.append(m_Button_Child);
  m_MyContainer.append(m_Label_Child);
  m_MyContainer.prepend(*Gtk::make_managed<Gtk::Label>(
    "First line\nSecond line\nThird line"));
  m_MyContainer.set_expand();
  m_VBox.append(m_MyContainer);

#if HAS_SIGNAL_DESTROY
  // A managed custom container.
  auto container = Gtk::make_managed<MyContainer>();
  container->prepend(*Gtk::make_managed<Gtk::Label>("Second custom container"));
  container->set_expand();
  m_VBox.append(*container);
#endif
  m_VBox.append(m_ButtonBox);

  m_ButtonBox.append(m_Button_Quit);
  m_ButtonBox.set_margin(6);
  m_Button_Quit.set_hexpand(true);
  m_Button_Quit.set_halign(Gtk::Align::END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
              &ExampleWindow::on_button_quit) );
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  set_visible(false);
}

File: main.cc (For use with gtkmm 4)

#include "examplewindow.h"
#include <gtkmm/application.h>

int main(int argc, char *argv[])
{
  auto app = Gtk::Application::create("org.gtkmm.example");

  //Shows the window and returns when it is closed.
  return app->make_window_and_run<ExampleWindow>(argc, argv);
}

File: mycontainer.cc (For use with gtkmm 4)

#include "mycontainer.h"

// This example container is a simplified vertical Box.
//
// It can't be used as a managed widget, managed by another container
// unless Gtk::Widget::signal_destroy() exists.
// It would cause an error like
// Gtk-WARNING **: 08:31:48.137: Finalizing gtkmm__GtkWidget 0x561b777462c0, but it still has children left:

MyContainer::MyContainer()
{
#if HAS_SIGNAL_DESTROY
  signal_destroy().connect(sigc::mem_fun(*this, &MyContainer::on_container_destroy));
#endif
}

MyContainer::~MyContainer()
{
  // If MyContainer is a managed widget, the underlying C object is destructed
  // before this C++ destructor is executed.
  if (!gobj())
    return;

  // If MyContainer is not a managed widget, unparent all children here.
  while (Widget* child = get_first_child())
    child->unparent();
}

#if HAS_SIGNAL_DESTROY
// This signal handler is called only if MyContainer is a managed widget.
void MyContainer::on_container_destroy()
{
  while (Widget* child = get_first_child())
    child->unparent();
}
#endif

// Get number of visible children.
int MyContainer::get_nvis_children() const
{
  int nvis_children = 0;
  for (const Widget* child = get_first_child(); child; child = child->get_next_sibling())
    if (child->get_visible())
      ++nvis_children;

  return nvis_children;
}

Gtk::SizeRequestMode MyContainer::get_request_mode_vfunc() const
{
  return Gtk::SizeRequestMode::HEIGHT_FOR_WIDTH;
}

// Discover the total amount of minimum space and natural space needed by
// this container and its children.
void MyContainer::measure_vfunc(Gtk::Orientation orientation, int for_size,
  int& minimum, int& natural, int& minimum_baseline, int& natural_baseline) const
{
  // Don't use baseline alignment.
  minimum_baseline = -1;
  natural_baseline = -1;

  minimum = 0;
  natural = 0;

  int dummy_minimum_baseline = 0;
  int dummy_natural_baseline = 0;

  if (orientation == Gtk::Orientation::HORIZONTAL)
  {
    int height_per_child = for_size;

    if (for_size >= 0)
    {
      // Number of visible children.
      const int nvis_children = get_nvis_children();

      // Divide the height equally among the visible children.
      if (nvis_children > 0)
        height_per_child = for_size / nvis_children;
    }

    // Request a width equal to the width of the widest visible child.
    for (const Widget* child = get_first_child(); child; child = child->get_next_sibling())
      if (child->get_visible())
      {
        int child_minimum_width = 0;
        int child_natural_width = 0;
        child->measure(orientation, height_per_child, child_minimum_width,
          child_natural_width, dummy_minimum_baseline, dummy_natural_baseline);
        if (child_minimum_width > minimum)
          minimum = child_minimum_width;
        if (child_natural_width > natural)
          natural = child_natural_width;
      }
  }
  else // Gtk::Orientation::VERTICAL
  {
    // The allocated height will be divided equally among the visible children.
    // Request a height equal to the number of visible children times the height
    // of the highest child.
    int nvis_children = 0;
    for (const Widget* child = get_first_child(); child; child = child->get_next_sibling())
      if (child->get_visible())
      {
        ++nvis_children;
        int child_minimum_height = 0;
        int child_natural_height = 0;
        child->measure(orientation, for_size, child_minimum_height,
          child_natural_height, dummy_minimum_baseline, dummy_natural_baseline);
        if (child_minimum_height > minimum)
          minimum = child_minimum_height;
        if (child_natural_height > natural)
          natural = child_natural_height;
      }
    minimum *= nvis_children;
    natural *= nvis_children;
  }
}

void MyContainer::size_allocate_vfunc(int width, int height, int baseline)
{
  //Do something with the space that we have actually been given:
  //(We will not be given heights or widths less than we have requested, though
  //we might get more.)

  // Number of visible children.
  const int nvis_children = get_nvis_children();

  if (nvis_children <= 0)
  {
    // No visible child.
    return;
  }

  //Assign space to the children:
  Gtk::Allocation child_allocation;
  const int height_per_child = height / nvis_children;

  //Place the first visible child at the top-left:
  child_allocation.set_x(0);
  child_allocation.set_y(0);

  //Make it take up the full width available:
  child_allocation.set_width(width);
  child_allocation.set_height(height_per_child);

  //Divide the height equally among the visible children.
  for (Widget* child = get_first_child(); child; child = child->get_next_sibling())
    if (child->get_visible())
    {
      child->size_allocate(child_allocation, baseline);
      child_allocation.set_y(child_allocation.get_y() + height_per_child);
    }
}

void MyContainer::append(Gtk::Widget& child)
{
   child.insert_at_end(*this);
}

void MyContainer::prepend(Gtk::Widget& child)
{
   child.insert_at_start(*this);
}

void MyContainer::remove(Gtk::Widget& child)
{
  child.unparent();
}