Create  Edit  FrontPage  Index  Search  Changes  History  RSS  Login

tut-gtk2-txtw-icw

Inserting Child Widgets

Inserting widgets into a text buffer is a little more involved than was with pixbufs, because you must notify both the text buffer and the text view to embed a widget. You begin by creating a Gtk::TextChildAnchor object with Gtk::TextBuffer#create_child_anchor, which is used to mark the placement of the widget within the Gtk::TextBuffer. Then you add the widget to the Gtk::TextView widget.

txtw-icw.png


childwidgets.rb

#!/usr/bin/env ruby
require 'gtk2'

window = Gtk::Window.new(Gtk::Window::TOPLEVEL)
window.resizable = true
window.title = "Child Widgets"
window.border_width = 10
window.signal_connect('delete_event') { Gtk.main_quit }
window.set_size_request(250, 100)

textview = Gtk::TextView.new
textview.buffer.text = "\n Click  to exit!"

# Create a new child widget anchor at the specified iterator.
iter = textview.buffer.get_iter_at_offset(8)
anchor = textview.buffer.create_child_anchor(iter)

# Insert a GtkButton widget at the child anchor.
button = Gtk::Button.new("the button")
button.signal_connect('clicked') { Gtk.main_quit }
textview.add_child_at_anchor(button, anchor)

scrolled_win = Gtk::ScrolledWindow.new
scrolled_win.border_width = 5
scrolled_win.add(textview)
scrolled_win.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS)

window.add(scrolled_win)
window.show_all
Gtk.main

Following are the three new methods we have used in our template example program:

Gtk::TextBuffer#get_iter_at_offset

get_iter_at_offset(char_offset)
Gets the iter to a position char_offset chars from the start of the entire buffer.
  • char_offset : char offset from start of buffer, counting from 0
  • Returns: a Gtk::TextIter

Gtk::TextBuffer#create_child_anchor

create_child_anchor(iter)
This is a convenience method which simply creates a child anchor with Gtk::TextChildAnchor.new and inserts it into the buffer with Gtk::TextBuffer#insert_child_anchor. The new anchor is owned by the buffer; no reference count is returned to the caller of Gtk::TextBuffer#create_child_anchor.

Gtk::TextView#add_child_at_anchor

add_child_at_anchor(child, anchor)
Adds a child widget in the text buffer, at the given anchor.
Last modified:2012/09/09 02:12:49
Keyword(s):
References:[tut-gtk2-txtw] [tut-gtk]