[cairo] Cairo with GTK GUI integration, getting inverse transformation matrix

Johannes Bauer dfnsonfsduifb at gmx.de
Mon Jan 18 13:04:02 PST 2016

Hi there,

I'm not sure wheter this question is more of a Cairo or more of a GTK3
question, but I tend to Cairo, so here it goes. If I'm wrong, please
tell me.

Currently I design a small application which has a vector graphics GUI.
Obviously, Cairo is perfectly suited for this. So I have a GTK3 GUI in
which the main part of the window is a GtkDrawingArea in which I draw
with Cairo using Python. So basically I listen for the draw() handler on
which I get passed a Cairo context.

I transform the cairo context as needed (to allow for panning and
zooming of the work area). In particular, I set a transformation matrix
before drawing all items:

M = cairo.Matrix(xx = self._zoom, yy = self._zoom)
self._cairo_ctx = cairo_ctx
for obj in self._objects:

(right now I'm neither panning nor do I handle partial redraws efficiently).

During the draw() signal handler call, if I print the result of
cairo_ctx.get_matrix(), I get a copy of the matrix M, with correct

Now someone presses the mouse in the screen and I would like to
transform from screen space into my logical space. So what I thought was
that I could, in the event handler for the mouse press, do:

(x, y) = self._cairo_ctx.device_to_user(screen_x, screen_y)

Unfortunately, this doesn't work: In this signal handler, the CTM is
always reset to the identity matrix. I suspect that the double buffering
creates the next Cairo context even before the new draw() handler is
called or something like that is going on.

Surely I'm not the first nor brightest person to try this. Could you
please help me out how this is supposed to work? I'd really appreciate it.

Best regards,

More information about the cairo mailing list