Embedding Python3 in Qt 5

Another way to avoid the conflict regarding 'slots', without the need for deactivating the keywords signals/slots/emit (which may be undesirable for large Qt projects), is to locally "park" the offending keyword while Python.h is included, and then reassign it. To achieve this, replace every occurrence of #include "Python.h" by the following block:

#pragma push_macro("slots")
#undef slots
#include "Python.h"
#pragma pop_macro("slots")

Or, more conveniently, put the above code in its own header, e.g. Python_wrapper.h, and replace all occurrences of #include "Python.h" by #include "Python_wrapper.h".


The offending line is this:

PyType_Slot *slots; /* terminated by slot==0. */

The problem is that with this line, "slots" is a keyword by default in Qt. In order to use that variable name in other projects, you will need to use this in your project file:

CONFIG += no_keywords

For details, see the documentation:

Using Qt with 3rd Party Signals and Slots

It is possible to use Qt with a 3rd party signal/slot mechanism. You can even use both mechanisms in the same project. Just add the following line to your qmake project (.pro) file.

CONFIG += no_keywords

It tells Qt not to define the moc keywords signals, slots, and emit, because these names will be used by a 3rd party library, e.g. Boost. Then to continue using Qt signals and slots with the no_keywords flag, simply replace all uses of the Qt moc keywords in your sources with the corresponding Qt macros Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), and Q_EMIT.