一、环境配置
    ubuntu 20.04.2.0
    qt 5.9.0
    python 3.8

    二、主要流程(“hello world”)

    1.创建c++ 和 python文件

    首先在qtcreator创建一个qt console application 主要流程 - 图1
    然后在项目中添加一个python文件 主要流程 - 图2
    最后项目结构如下图所示
    图片.png

    2.修改python和c++文件

    修改ccy_py.py文件如下

    1. #!/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. def hello():
    4. print("hello world!")

    修改main.cpp文件如下

    1. #include <QCoreApplication>
    2. #include <Python.h>
    3. #include <iostream>
    4. using namespace std;
    5. int main(int argc, char *argv[])
    6. {
    7. QCoreApplication a(argc, argv);
    8. Py_Initialize();
    9. if ( !Py_IsInitialized() )
    10. {
    11. return -1;
    12. }
    13. PyObject* pModule = PyImport_ImportModule("test_py"); // 这里的test_py就是创建的python文件
    14. if (!pModule) {
    15. cout<< "Cant open python file!\n" << endl;
    16. return -1;
    17. }
    18. PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); // 这里的hellow就是python文件定义的函数
    19. // PyObject* pDict = PyModule_GetDict(pModule);
    20. // if (!pDict) {
    21. // printf("Cant find dictionary.\n");
    22. // return -1;
    23. // }
    24. // PyObject* pFunhello = PyDict_GetItemString(pDict, "hello");
    25. if(!pFunhello){
    26. cout<<"Get function hello failed"<<endl;
    27. return -1;
    28. }
    29. PyObject_CallFunction(pFunhello,NULL);
    30. Py_Finalize();
    31. return a.exec();
    32. }

    在.pro文件界面右击,点击添加库
    图片.png

    点击外部库
    图片.png

    图片.png

    库文件:usr/lib/python3.8/config-3.8m-x86_64-linux-gnu 然后选择libpython3.8a.图片.png
    包含路径:/usr/include/python3.8
    图片.png

    构建项目+qmake+运行
    图片.png

    无数报错
    图片.png
    首先解决意外的标记位于“;”之前
    图片.png

    由于QT中定义了slots作为关键了,而python3中有使用slot作为变量,所以在编译时会有冲突。
    需要修改python库中的object.h文件,因为该文件是系统文件,可以在终端中sudo gedit进行修改:

    1. sudo gedit /usr/include/python3.8/object.h
    1. typedef struct{
    2.       const char* name;
    3.       int basicsize;
    4.       int itemsize;
    5.       unsigned int flags;
    6.       
    7. #undef slots //这里取消slots宏定义
    8.       PyType_Slot *slots;  /* terminated by slot==0. */
    9.       #define slots Q_SLOTS  //这里恢复slots宏定义与QT中QObjectDefs.h中一致
    10.   } PyType_Spec;

    重新构建然后,然后我来自未来?(一直处在构建过程)图片.png