一、环境配置
ubuntu 20.04.2.0
qt 5.9.0
python 3.8
二、主要流程(“hello world”)
1.创建c++ 和 python文件
首先在qtcreator创建一个qt console application 
然后在项目中添加一个python文件 
最后项目结构如下图所示 
2.修改python和c++文件
修改ccy_py.py文件如下
#!/usr/bin/env python# -*- coding: utf-8 -*-def hello():print("hello world!")
修改main.cpp文件如下
#include <QCoreApplication>#include <Python.h>#include <iostream>using namespace std;int main(int argc, char *argv[]){QCoreApplication a(argc, argv);Py_Initialize();if ( !Py_IsInitialized() ){return -1;}PyObject* pModule = PyImport_ImportModule("test_py"); // 这里的test_py就是创建的python文件if (!pModule) {cout<< "Cant open python file!\n" << endl;return -1;}PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); // 这里的hellow就是python文件定义的函数// PyObject* pDict = PyModule_GetDict(pModule);// if (!pDict) {// printf("Cant find dictionary.\n");// return -1;// }// PyObject* pFunhello = PyDict_GetItemString(pDict, "hello");if(!pFunhello){cout<<"Get function hello failed"<<endl;return -1;}PyObject_CallFunction(pFunhello,NULL);Py_Finalize();return a.exec();}
在.pro文件界面右击,点击添加库
点击外部库

库文件:usr/lib/python3.8/config-3.8m-x86_64-linux-gnu 然后选择libpython3.8a.
包含路径:/usr/include/python3.8
构建项目+qmake+运行
无数报错
首先解决意外的标记位于“;”之前
由于QT中定义了slots作为关键了,而python3中有使用slot作为变量,所以在编译时会有冲突。
需要修改python库中的object.h文件,因为该文件是系统文件,可以在终端中sudo gedit进行修改:
sudo gedit /usr/include/python3.8/object.h
typedef struct{const char* name;int basicsize;int itemsize;unsigned int flags;#undef slots //这里取消slots宏定义PyType_Slot *slots; /* terminated by slot==0. */#define slots Q_SLOTS //这里恢复slots宏定义与QT中QObjectDefs.h中一致} PyType_Spec;
重新构建然后,然后我来自未来?(一直处在构建过程)
