1

I work on GUI project(http://smartdict.net) based on ruby-gnome2. I want to insert a web link into Gtk::TextBuffer element. How can I do that?

It's a ruby project but solutions on C or Python would be useful as well. Thanks.

Sergey Potapov
  • 3,819
  • 3
  • 27
  • 46

2 Answers2

3

This is how I did it:

As Micah said, you create a tag that makes the text look like a link (blue and underlined). Then connect a signal to the TextView, so when the user clicks on it, it will call a method to open the url. You'll need to devise a way for the method to know the link to open by keeping track of them in an array, or parsing the link based on the cursor position. That part is up to you.

class myTextView  < Gtk::TextView

  def initialize
    signal_connect("button_release_event") { open_url() }   
    buffer.create_tag("blue", { "foreground" => "#0000FF", "underline" => Pango::UNDERLINE_SINGLE  })
    start_iter, end_iter = get_line_iters()
    buffer.apply_tag("blue", start_iter, end_iter)
  end

  def open_url()
     # open link here
  end

end

This is a standard Gtk solution. I would suggest using visualruby:

http://visualruby.net

user1182000
  • 1,625
  • 14
  • 12
  • I like the simplicity of this. I did not think of checking for mouse-button-events. When I read it, the rest was simple to do (I have to custom parse the whole buffer anyway). By the way, what happened to visual ruby? – shevy Jan 19 '21 at 05:01
2

While I haven't done this myself, I would imagine you could do it 2 ways:

  1. Style the text yourself (blue with an underline) using text tags and handle the launching of the URL yourself.

  2. Use a gtk_text_buffer_insert_child_anchor to specify where in the buffer to insert the link, and then gtk_text_view_add_child_at_anchor to insert a GtkLinkButton into the text view.

Micah Carrick
  • 9,967
  • 3
  • 31
  • 43
  • Hi Micah. Thanks for your great tutorials on adding GUIs to ruby. You inspired me to write visualruby.net. Your tutorial was my first exposure to it. Thanks! – user1182000 Jun 18 '12 at 20:15