Archive for the 'Python' Category

Getting PyQt4 to work on Snow Leopard

Saturday, November 7th, 2009

I recently upgraded my Mac to OS 10.6 and I had to rebuild Qt and PyQt to get them working again. I installed Qt 4.5.3 from source and then installed sip 4.9.1 and PyQt4.6.1. Immediately it failed to work with the following error:

>>> from PyQt4 import QtCore
Traceback (most recent call last):
  File "", line 1, in 
ImportError: dlopen(/Library/Python/2.6/site-packages/PyQt4/QtCore.so, 2): Symbol not found: _sipQtConnect
  Referenced from: /Library/Python/2.6/site-packages/PyQt4/QtCore.so
  Expected in: flat namespace
 in /Library/Python/2.6/site-packages/PyQt4/QtCore.so

Some quick searching led me to this post, which implied that hacking PyQt’s configure.py file to force the architecture to be 64-bit would do the trick.
So where it says:

for a in sipcfg.arch.split():
    if a == 'i386':
        qmake_archs.append('x86_64')
    elif a == 'x86_64':
        qmake_archs.append('x86_64')
    elif a == 'ppc':
qmake_archs.append('ppc')

Replace qmake_archs.append('x86') with qmake_archs.append('x86_64').
Now PyQt works again.

2D Transforms and QGraphicsScene

Monday, August 18th, 2008

QGraphicsScene and QGraphicsItems use the QTransform class to move, scale, shear, and rotate objects in the view. For the most part, this works great. Things get a little tricky when you want to keep track of an item’s rotation in terms of a simple angular value. QGraphicsItem doesn’t have a method to get the “rotation,” and neither does QTransform. Instead we have to recover it from the transformation matrix.

The QTransform docs tell us that a rotation is measured in the clockwise direction. Rotation by an angle ? is computed for a given point using the matrix:

How to recover the angular rotation from this matrix? One way is to apply the same matrix to a point at x=0, y=1 and use some simple trig to figure out the angle between its original and new positions.

Enter the excellent atan2 function. Written in python, the math looks like this:

rotation = 180./math.pi * math.atan2(-xform.m21(), xform.m11())

Where xform is our QTransform object (the transformation matrix).

I wrote a little program, “Xformer,” in PyQt that demonstrates the relationship between an object’s QTransform matrix and its corresponding transformation, rotation, scale, and shear values.

Download Xformer and try it out. It requires a working copy of PyQt4.