Embedding Python in Qt 5

与世无争的帅哥 提交于 2019-12-07 01:38:34

问题


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

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

#include <Python.h>

at the top (below Qt headers) the compilation breaks 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 Python header above the Qt headers it breaks with

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 happens? I could be because Qt and Python define some common words? What can I do about it?


回答1:


This happens because including Python.h first indirectly includes termios.h, which defines B0 to be 0, which in turn qpagedpaintdevice.h want's to use as a variable name. Including Python.h after the Qt includes does pretty much the same thing the other way around with the string 'slots'.

I suggest the following order:

#include <Python.h>
#undef B0
#include <QWhatEver>



回答2:


An alternative to the accepted answer:

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

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

The drawback is then that you will need to refer to the corresponding Qt macros instead of the previous keywords.

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

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

PS: This is normally a good option when starting a new project, not when adding Python to an existing code base that uses the Qt keywords extensively.



来源:https://stackoverflow.com/questions/15078060/embedding-python-in-qt-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!