Problem
By default, GtkTreeView sets the tab at every eighth character as shown below:
Suppose you would like to set the tab position at every fourth character instead as shown below:
Solution
- Create a new PangoTabArray on the GtkTreeView.
- Calculate the width of the font. With this information, we can calculate the width in pixels for every fourth character.
- Set each tab position with PangoTabArray::set_tab()
- Then impose the tabs on the textview with GtkTextView::set_tabs() on the GtkTreeView.
Sample Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18 19 20 21 22 23 24 25 30 31 32 33 34 35 36 37 38 39 42 43 44 46 47 48 49 50 51 52 53 54 60 61 62 63 | <?php $window = new GtkWindow(); $window->set_size_request(400, 240); $window->connect_simple('destroy', array('Gtk','main_quit')); $window->add($vbox = new GtkVBox()); // display title $title = new GtkLabel("Set the Tab Position of GtkTextView\n". "Part 2 - at every 4th character"); $title->modify_font(new PangoFontDescription("Times New Roman Italic 10")); $title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff")); $title->set_size_request(-1, 40); $title->set_justify(Gtk::JUSTIFY_CENTER); $alignment = new GtkAlignment(0.5, 0, 0, 0); $alignment->add($title); $vbox->pack_start($alignment, 0, 0); $vbox->pack_start(new GtkLabel(), 0, 0); // Create a new buffer and a new view to show the buffer. $buffer = new GtkTextBuffer(); $view = new GtkTextView(); $view->set_buffer($buffer); $view->modify_font(new PangoFontDescription("Courier New 16")); // note 6 $view->set_wrap_mode(Gtk::WRAP_WORD); $buffer->set_text("123456781234567812345678\n"); $scrolled_win = new GtkScrolledWindow(); $scrolled_win->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); $vbox->pack_start($scrolled_win); $scrolled_win->add($view); $window->show_all(); $style = $view->get_style(); $font = $view->get_style()->font_desc; $font_size_in_pango_unit = $font->get_size(); // note 1 $font_size_in_pixel = $font_size_in_pango_unit/1024; // note 2 $tabs = new PangoTabArray(0, true); $index = 0; for ($i=0; $i<400; $i=$i+$font_size_in_pixel*4) { // note 3 $tabs->set_tab($index, PANGO::TAB_LEFT, $i); // note 4 ++$index; print "pos $index: $i\n"; } $view->set_tabs($tabs); // note 5 Gtk::main(); ?> |
Output
As shown above.
Explanation
- Get the font size. Note that this is in pango unit.
- Convert from pango unit to pixels.
- Note that we are using fixed-width font here. So we simply multiply the font width by 4.
- Set the tab positions. In this example, we set a tab for every 100 pixels.
- Set the tab on the treeview.
- Try changing this to other font size. You will see that the tab will always be set at every fourth character.
Read more...