Thursday, 19 November 2009

regex saves the pyqt day

I'm developing openmolar on Ubuntu Karmic, and that creates some backwards compatibility issues for hardy, intrepid and jaunty with code generated by pyuic4.

so I have to make some substitutions, and that's where regex comes in.
the python regex module is "re", and I am using a few of it's features here. Anyways, I'll let the code speak for itself.

the problem is to turn generated code like this (on pyqt 4.6 where native python integers are acceptable)
spinBox.setProperty("value", 8)
progressBar.setProperty("value", 10)
randomWidget.setProperty("value", 260)
into this....
spinBox.setProperty("value", QtCore.QVariant(8))
progressBar.setProperty("value", QtCore.QVariant(10))
randomWidget.setProperty("value", QtCore.QVariant(260)
Here's one way to do it...
import re

matches = re.finditer('setProperty\("value", (\d+)\)', data)
for m in matches:
    data = data.replace(m.group(), "QtCore.QVariant(%s)"% m.groups()[0])

my script for compiling any qt-designer generated ui files into python code can be found here the above code is in lines 38 - 48.

No comments: