以下内容是参考博客:https://blog.csdn.net/alxe_made/article/details/83382159
由以上大神的博客作为参考成功实现的
一、先说几点注意的地方:
1、就是需要将python的路径在pro中加载进来,这边使用的是绝对路径,因为每个人安装python的安装路径不一样,所以
这个是第一个坑,需要自己去手动修改
2、就是成功引入进来之后,会发现编译的时候还会提示个错误,这个据说是由于信号和槽冲突造成的,具体的就是加上两句代码
来解决
3、非常重要的一个坑,就是你的qt编译加载的运行必须是64位的,因为我这边安装的python就是64位的,所以如果你的qtcreator编译运行不是64位的话,整个程序就可能出现莫名其妙的问题,这是一个非常重要的坑提示
二、开始进行环境的搭建
1、 qtcreator中新建个模板,如下:
2、新建个test_py.py文件夹,可以在qtcreator中通过加载新文件的形式来进行加载进来,最后实现的文件目录如下:
test_py.py中的代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def hello():
print("hello world121♪(^∀^●)ノ!")
3、开始在qtcreator的pro中进行加载python的路径 ,如下:
4、在main.cpp中加入代码如下:
#include <QCoreApplication>
#include <Python.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//初始化python模块
Py_Initialize();
if ( !Py_IsInitialized() )
{
return -1;
}
//导入test.py模块
PyObject* pModule = PyImport_ImportModule("test_py");
if (!pModule) {
printf("Cant open python file!\n");
return -1;
}
//获取test模块中的hello函数
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello");
//注释掉的这部分是另一种获得test模块中的hello函数的方法
// 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;
}
//调用hello函数
PyObject_CallFunction(pFunhello,NULL);
//结束,释放python
Py_Finalize();
return a.exec();
}
5、编译的时候出现如下错误:
加上两句代码如下:
6、再编译发现报错如下:
这个时候,我们就需要将test_py文件放到生成的build中的exe的同级目录下,这样,才能成功找到!
源码中的在不同的电脑中的修改点:1、更改python的路径,2、需要将test_py文件放到build的同级exe的目录下
qt5.13.2+VST017
源码链接:https://download.csdn.net/download/Littlehero_121/12707474