Revision 3 as of 2008-11-15 14:00:11

Clear message

Oleksandr Yakovlyev's Embeding PyQt Tutorial

This is a short tutorial to embed PyQt in your Qt application. It assumes knowledge of bash, Python, Qt+PyQt and sip.

Problem

One day I discovered that I need to use PyQt scripts in a Qt application. It assumes that I want to use C++ calls of my core application, create new classes/objects with python/pyqt and connect signal/slots beetween two parts of the application (Qt and PyQt)

First problem is event loop. Python and Qt application have their own event loop, and I have not found way to use only Qt event loop yet. So we need to use Python event loop (It means that we use PyQt event loop). So I changed my Qt application with next way:

My application doesn't have critical code in qt main.cpp so it was easy. The modification doens't create speed problem because all code is C++ still.

Now application compiles into shared library. Let's try it with Qt example (examples/application)

application.h

Here I have added signal void runScript(const QString&)

application.cpp

I added a toolbutton "Run Script". Text of script is content of QTextEdit (editor of application example)

Now we can create pro file. Remember that our qt application is shared library now.

application.pro

So, we have compiliable small qt application with editor and button "Run Script". Let us to make wrapping for the application. We create dir "coreappwrap" where we put wrapping generated with sip. Now we create sip file for our wrappings:

coreapp.sip

Note, that we use #include "../application.h" because sip generates files to coreappwrap/. It is important to wrap our signal runScript, because it will be used in python part.

Now we create configure.py according to Phil Thompson manual

configure.py

We used -Wl,-rpath,. and -Wl,-rpath,.. because generated python module located in coreappwrap directory. makefile.extra_libs = coreapp is our Qt application that we have created with application.pro. It is libcoreapp.so.XXX files

Now it is time to compile that all. First build our Qt application:

It creates libcoreapp.so.XXX in "." directory

Let's prepare wrappings:

It creates wrappings files in coreappwrap

And compile them

It creates coreappwrap/coreappwrap.so. It is python module.

At the end we need to write main.py to run it all

main.py

Note that "exec" see MainWindow variable and user have access to it with scripts. You can use other variables you want to be acceessed by scripts, etc

The example (tarball ) is located at http://yshurik.kiev.ua/PyQtScripting.tar.gz, 4k (link error) http://yshurik.kiev.ua/PyQtScripting.zip, 4k

You may also make corrections to this page. If you have questions or comments, send them to me at yshurik@uael.com.ua.

Unable to edit the page? See the FrontPage for instructions.