Python embedding in Qt 5

I would like to embed a Python interpreter in a Qt 5 application.

I have a working application in Qt 5, but when I put

#include <Python.h> 

at the top (below the Qt headers) compilation is interrupted with

 ../sample/python3.3m/object.h:432:23: error: expected member name or ';' after declaration specifiers PyType_Slot *slots; /* terminated by slot==0. */ ~~~~~~~~~~~ ^ 

When I put the Python header over the Qt headers, it breaks into

 In file included from ../Qt5.0.1/5.0.1/clang_64/include/QtGui/QtGui:59: ../Qt5.0.1/5.0.1/clang_64/include/QtGui/qpagedpaintdevice.h:63:57: error: expected '}' A0, A1, A2, A3, A5, A6, A7, A8, A9, B0, B1, ^ /usr/include/sys/termios.h:293:12: note: expanded from macro 'B0' #define B0 0 ^ ../Qt5.0.1/5.0.1/clang_64/include/QtGui/qpagedpaintdevice.h:62:19: note: to match this '{' enum PageSize { A4, B5, Letter, Legal, Executive, ^ 1 error generated. 

Please, does anyone know why this is happening? Maybe because Qt and Python define some common words? What can i do with this?

+6
source share
2 answers

This is because, including Python.h, it first indirectly includes termios.h, which defines B0 as 0, which, in turn, qpagedpaintdevice.h wants to use as a variable name. Enabling Python.h after enabling Qt does pretty much the same thing as in other slots.

I suggest the following order:

 #include <Python.h> #undef B0 #include <QWhatEver> 
+6
source

Alternative to accepted answer:

Since Qt uses slots as reserved keywords, there is a collision with the declaration of the slots member of the PyType_Spec structure in the Python API.

Qt may be instructed not to use the normal moc keyword, and this will eliminate the collision. This is done by adding the following to the project file: CONFIG += no_keywords

The downside is that you will need to reference the corresponding Qt macros instead of the previous keywords.

Thus, for the Qt side, the following replacements will be required: signals -> Q_SIGNALS slots -> Q_SLOTS emit -> Q_EMIT

This is explained in the Qt docs on signals and slots in the section Using Qt with Signals and Slots in Part Three .

PS: This is usually a good option when starting a new project, rather than adding Python to an existing code base that makes extensive use of Qt keywords.

+2
source

All Articles