Writing Qt apps in python
Writing Qt apps in Python with Qt3 worked. Somewhat. I never found the energy to get it all set up. Finally with Qt4 we have something that “just works”. At least on Ubuntu and Windows (haven’t tested anywhere else).
Yes, since version 4, trolltech finally decided to release Qt as well under the GPL. To most of you it’s all old news. But hey…. just felt like writing it down again 😉
The problems with SIP are finally gone. So you just install python, Qt4 and pyqt4 and off you go.
Writing apps is actually a breeze. You fire up the Qt-Designer, drag and drop some widgets on your form, and save the Form as a .ui file.
Next you generate the python-code for the form with pyuic4. Let’s say you created “MainForm.ui”. The you just do:
Actually the name “ui_mainform.py” is fully up to you.
But this script does not have an entry-point, so just typing “python ui_mainform.py” will silently return. For those of you that just thought: “Hey, I read the man-page, and used the “-x” parameter with pyuic4″. Sure. You can do that. But you shouldn’t. Just bear with me a second.
The cleanest way to run your application is to write a startup script. A copy/paste example:
from PyQt4 import QtCore, QtGui
from ui_mainform import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
So why not just “pyuic4 -x” ?
Simple. Whenever you run this, you will overwrite your old code. And you will inevitably want to complement your user-interface with some program logic. Otherwise your application won’t do much. So if you put your business-logic into the generated code, you will always end up cutting and pasting things about. And that clearly violates the “Don’t repeat yourself” dogma. So: You be nice, take the startup script and stick your logic in there. Like that you can recreate/regenerate the user-interface from the .ui file without ever (well… nearly) touching yor business-logic-code.
For some programming examples, head right over to Riklaunim’s TechBlog. There’s some most excellent examples for pyqt4. You might see, I “borrowed” the startup script from there too!
A note for Windows users
To get python and Qt working, you need to take care of the version numbers mentioned in the file names of pyqt. Please use the proper Qt version with your pyqt download
As you might have noticed, you also need MingW (a free GNU build environment for windows. Includes C-compiler, libraries, yadda yadda…). Somewhere along the installation, you might get an error nagging you about the win32api. You can happily ignore this and just continue. I have not yet encountered any problems.
Posted in Python | No Comments »
