There is a nice example in the Python GTK+ 3 Tutorial, TextView Example
But to make it clearer (hopefully) on the important parts, as you have guessed you have to use text tags, you have to define those in the TextBuffer, not in the TextView, e.g.
self.tag_bold = self.textbuffer.create_tag("bold", weight=Pango.Weight.BOLD)
and then you can apply your tag to the portion of text that you want to make bold, in order to do that you will have to provide to the TextBuffer.apply_tag() method the bounds (start, end) of that portion of text, like:
start, end = self.textbuffer.get_selection_bounds()
self.textbuffer.apply_tag(self.tag_bold, start, end)
and you will be all set.
In the above example the bounds are taken by the portion of text selected by the user, but of course if you are displaying a read-only text you can provide the bounds yourself in the code, look at the TextBuffer documentation.
You can also add the text with valid pango markup by the method:
self.textbuffer.insert_markup(iter, markup)
Would be nice if the method could return the new iter pointing at the end of the inserted text, which would makes life a lot easier, but the method comes from plain introspection, it would require an override to act like that.
See the minimal example here below (you can make it way nicer):
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
class TextViewWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="TextView Example")
self.set_default_size(-1, 350)
self.grid = Gtk.Grid()
self.add(self.grid)
self.create_textview()
def create_textview(self):
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
self.grid.attach(scrolledwindow, 0, 1, 3, 1)
self.textview = Gtk.TextView()
self.textbuffer = self.textview.get_buffer()
start_iter = self.textbuffer.get_start_iter()
self.textbuffer.insert(start_iter, "This is some text ")
self.textbuffer.insert_markup(self.textbuffer.get_end_iter(), "<b>and some bold text</b>", -1)
scrolledwindow.add(self.textview)
win = TextViewWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()