Ubuntu: Change font programmatically for GTK3 TextView (quickly-widgets TextEditor)


In an app using PyGI and GTK3, I'm trying to let the user set the font family and size in a TextView through my app's settings dialog. In PyGI the TextView object has "set" methods for several properties, but not for font properties. I can set the font family via CSS using a CSS style provider. But I can't change that CSS dynamically to respect the font selected by a user. So how can I do this? (Note that the widget in question is actually the TextEditor from the quickly-widgets package and I'm using Quickly to build the app.)

Edit to clarify: I'm not wedded to using CSS, that just seems to be GTK's preferred approach. What I'm hoping for is a method of some kind, like GtkTextView.setFontProperties() or something like that. I can't find anything like that for font properties.




You can set the font in a textview using GTK+'s built-in button and dialog for this, Gtk.FontButton():

#!/usr/bin/python    from gi.repository import Gtk    class TextViewWindow:      def __init__(self):          self.window = Gtk.Window()          self.window.set_default_size(400, 400)            main_vbox = Gtk.VBox(homogeneous=False, spacing=0)          self.window.add(main_vbox)            self.tview = Gtk.ScrolledWindow()          main_vbox.add(self.tview)            self.textview = Gtk.TextView()          self.textbuffer = self.textview.get_buffer()          self.textbuffer.set_text("Here is a text view.")          self.textview.set_wrap_mode(Gtk.WrapMode.WORD)            self.tview.add(self.textview)            self.font_button = Gtk.FontButton()          self.font_button.connect('font-set', self.on_font_set)          main_vbox.pack_start(self.font_button, False, False, 0)            self.window.show_all()          self.window.connect('destroy', lambda w: Gtk.main_quit())        def on_font_set(self, widget):          font_description = widget.get_font_desc()          print "You chose: " + widget.get_font()          self.textview.modify_font(font_description)    def main():      app = TextViewWindow()      Gtk.main()    if __name__ == "__main__":      main()  

My demo:


Built-in dialog:



You should be able to use texttags to do this, but I'm not sure it's the "best" way.

First you would select all the text, here's the page from the readthedocs site on applying tags.

And here's a list of properties from the C/C++ reference.

Just adding this on... I recently needed to do something similar, and I had to do a little looking to come up with this snippet:

self.textview = Gtk.TextView()  self.textview.override_font(      Pango.font_description_from_string('DejaVu Sans Mono 12')      )  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »