Search code examples
pythongtk3pygobject

PyGTK 3 (gi.repository) PangoCairo changing color between drawing text and line


I'm having problems in changing colors between text and lines in a PangoCairo DrawingArea. They both come out the same color. Here is simple Python code:

from gi.repository import Gtk, Pango, PangoCairo

class Bug(Gtk.DrawingArea):
    def __init__ (self):
        Gtk.DrawingArea.__init__(self)

    def do_draw_cb(self, widget, cr):
        cr.translate ( 10, 10)

        layout = PangoCairo.create_layout (cr)
        desc = Pango.font_description_from_string ("Sans 14")
        layout.set_font_description( desc)
        cr.set_source_rgba(0.0, 1.0, 0.0, 1.0)
        layout.set_text("It is not easy being green", -1 )

        cr.move_to(40, 20)
        cr.line_to(70, 20)
        cr.set_source_rgba(0.0, 0.0, 0.0, 1.0)  # messes up previous set_text
        cr.stroke()
        PangoCairo.show_layout (cr, layout)

def destroy(window):
        Gtk.main_quit()

window = Gtk.Window()
window.set_title ("Green?")

app = Bug()
app.set_size_request (300, 200)

window.add(app)

app.connect('draw', app.do_draw_cb)
window.connect_after('destroy', destroy)
window.show_all()
Gtk.main()

If I remove the second set_source_rgba, then both the text and the line are green instead of both black. But what I want is the text in green and the line in black. How do I do this?


Solution

  • For layout, the color is read when you call show_layout, so the first set_source_rgba is effect-less. You should show the layout just after you set it's color.

      def do_draw_cb(self, widget, cr):
          cr.translate ( 10, 10)
    
          layout = PangoCairo.create_layout (cr)
          desc = Pango.font_description_from_string ("Sans 14")
          layout.set_font_description( desc)
          cr.set_source_rgba(0.0, 1.0, 0.0, 1.0)
          layout.set_text("It is not easy being green", -1 )
          PangoCairo.show_layout (cr, layout)
    
          cr.move_to(40, 20)
          cr.line_to(70, 20)
          cr.set_source_rgba(0.0, 0.0, 0.0, 1.0)  # messes up previous set_text
          cr.stroke()