由于工作的需要,有个项目需要在Qt中调用python,弄了半天各种出问题最后找到一位大佬文章传送门完美解决了这个问题。
// .pro中
INCLUDEPATH += -I C:\python10\include
LIBS += -LC:\python10\libs\ -lpython310
```cpp
#include <QApplication>
#include <Python.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
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文件定义的函数
if(!pFunhello){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject_CallFunction(pFunhello,NULL);
Py_Finalize();
return a.exec();
}
注意这里名字一定要_py.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def hello():
print("hello world!")
如果是没有找到文件需要在build哪里复制一份,如图
代码我放在这里–>gite
需要传递参数的例子(但是这个很乱)
详细原理Py_BuildValue