cgtkgtk3lablgtk

Gtk3 `set_fixed_height_from_font` does not produce cells of correct height


I am trying to make a tree view in Gtk3 such that each row has the size of two rows of text. The following is a minimal working example:

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
  GtkWidget *window;
  gtk_init(&argc, &argv);
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_default_size(GTK_WINDOW(window), 100, 100);

  /* init store */
  GtkListStore *store;
  store = gtk_list_store_new(1, G_TYPE_STRING);

  /* add items */
  int COL = 0;
  GtkTreeIter iter1, iter2;
  gtk_list_store_append(store, &iter1);
  gtk_list_store_set(store, &iter1, COL, "hello", -1);
  gtk_list_store_append(store, &iter2);
  gtk_list_store_set(store, &iter2, COL, "world", -1);

  /* make tree view */
  GtkWidget *list;
  GtkWidget *vbox;
  vbox = gtk_vbox_new(FALSE, 0);
  list = gtk_tree_view_new();
  gtk_box_pack_start(GTK_BOX(vbox), list, TRUE, TRUE, 0);
  gtk_container_add(GTK_CONTAINER(window), vbox);

  /* make column */
  GtkCellRenderer *renderer;
  GtkTreeViewColumn *column;
  renderer = gtk_cell_renderer_text_new ();
  column = gtk_tree_view_column_new_with_attributes("Items",
          renderer, "text", COL, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
  gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));

  /********* This doesn't work as expected! *********/
  gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(renderer),2);

  /* main */
  g_signal_connect(G_OBJECT (window), "destroy",G_CALLBACK(gtk_main_quit), NULL);
  gtk_widget_show_all(window);
  gtk_main();
  return 0;
}

I am using set_fixed_height_from_font to set the height based on the font. Now the above produces

enter image description here

which has entries of size one rather than two.

Is this a bug in Gtk, or am I doing something wrong?


Solution

  • set_fixed_height_form_font works in Gtk2, but behaves differently in Gtk3.

    My solution (in the OCaml interface, as originally posted), was to compute the height explicitly following cell_renderer_text.get_size:

    let default_font = "11"
    
    let calc_font_height ?(ypad = 0) (num_lines : int) : int =
      let fm = Cairo_pango.Font_map.get_default () in
      let ctx = Cairo_pango.Font_map.create_context fm in
      let fd = Pango.Font.from_string default_font in
      let metrics = Pango.Context.get_metrics ctx fd None in
      let ascent = Pango.Font.get_ascent metrics in
      let descent = Pango.Font.get_descent metrics in
      GPango.to_pixels((GPango.from_pixels ypad) + (num_lines * (ascent + descent)))
    

    then we set the attributes

    (GTree.cell_renderer_text [`FONT default_font; `YPAD 2;
                               `HEIGHT (Font.calc_font_height ~ypad:2 2)],
                              ["text",col])