Question

I would like to embed Python interpreter 3.4 into a Qt 5.2.1 application (64-bit). However I'm having build issues, I mean when I include Python header in the main.cpp it compiles fine.

#include <python.h>
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  return a.exec();
}

but when I put it anywhere else (after Qt headers)

//
// embedpytest.cpp
//
#include <QLibrary>
#include <python.h>


EmbedPyTest::EmbedPyTest()
{
}

I get compile errors:

C:\Python34\include\object.h:435: error: C2059: syntax error : ';'
C:\Python34\include\object.h:435: error: C2238: unexpected token(s) preceding ';'

enter image description here

It's very similar problem to this one, but the solution is not working

Embedding Python in Qt 5

Anyone knows how to solve this issue ? or suggest some clean workaround so that python.h and Qt5 can live together happily ever after ?

Was it helpful?

Solution 2

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.

OTHER TIPS

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top