Problem
You want to allow users to insert images in a GtkTextView as shown below:
Solution
- Load the image with GtkImage::new_from_file.
- Create an anchor in GtkBuffer using GtkTextbuffer::create_child_anchor().
- Add the image at the anchor location using GtkTextview::add_child_at_anchor().
Sample Code
The following image files are required by the sample code below. Please save a copy of the image files and put them in the same directory where you store the sample code.
icon_smile.gif | |
icon_lol.gif | |
icon_cool.gif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 19 23 24 25 26 27 28 37 38 40 41 42 43 44 46 47 48 49 50 51 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | <?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("Insert images in GtkTextView\n". "Click on the Emoticons to insert the smileys"); $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.5, 0, 0); $alignment->add($title); $vbox->pack_start($alignment); // Setup TextView $buffer = new GtkTextBuffer(); $view = new GtkTextView(); $view->set_buffer($buffer); $view->modify_font(new PangoFontDescription("Arial 10")); $view->set_wrap_mode(Gtk::WRAP_WORD); $hbox = new GtkHBox(); $hbox->pack_start(new ClickableImage('icon_smile.gif'), 0); // note 2 $hbox->pack_start(new ClickableImage('icon_lol.gif'), 0); // note 2 $hbox->pack_start(new ClickableImage('icon_cool.gif'), 0); // note 2 $vbox->pack_start($hbox, 0); $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(); Gtk::main(); class ClickableImage extends GtkEventBox { // note 1 function __construct($img_filename) { parent::__construct(); $img = GtkImage::new_from_file($img_filename); $this->add($img); $this->connect('button-press-event', array($this, 'on_button'), $img_filename); // note 3 } function on_button($widget, $event, $img_filename) { global $buffer, $view; $cursor_pos = $buffer->get_mark('insert'); // note 4 $iter = $buffer->get_iter_at_mark($cursor_pos); // note 4 $img = GtkImage::new_from_file($img_filename); // note 5 $anchor = $buffer->create_child_anchor($iter); // note 6 $view->add_child_at_anchor($img, $anchor); // note 7 $img->show(); } } ?> |
Read more...