Retrieve the window object from widgets with pygobject / GTK+3

I’m trying to develop a simple app using PyGObject, pyGTK as we used to call it last time I used it.

I must say that I mildly hate Gnome 3 (and Unity, for that matters) and even though there’s certainly been an improvement in the overall quality of the API for GTK+3 the lack of documentation and good tutorials is very depressing. One must always fall back to C documentation and hope that a python function exists with a similar name, or struggle through the source code to look for it.

Rant aside, one thing I wanted to do is to draw on a DrawingArea using Cairo whenever the mouse cursor enters some region. Once I got Glade to signal the motion-notify-event correctly (you have to both set the signal on the ‘signals’ tab and check the option for ‘Pointer Motion’ in the ‘Common’ tab under ‘Events’) I realized that you must create a Cairo context every time the signal handler is called, so that you can draw on it.

Googling and googling (and after stumbling upon the best source for what I wanted to do… even though it’s in Japanese! :D) I found that the easiest solution is to call something like

def onMouseMove(self, widget, event):
  cr = widget.window.cairo_create()

Unfortunately, an AttributeError: 'DrawingArea' object has no attribute 'window' came up, so after more googling I found out that the new fashion is to call get_property("propertyName") to retrieve its fields… which is not bad in and on itself (if not a little too weakly-typed for my tastes), but it’s not that immediate if you were used to code for GTK+2.

This is what I finally came up with:

def onMouseMove(self, widget, event):
  cr = widget.get_property('window').cairo_create()

Now I just have to do the rest… 🙂


2 thoughts on “Retrieve the window object from widgets with pygobject / GTK+3

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s