在调用Python脚本时,先将Python的库文件以及头文件导入
LIBS += -LC:/Users/Ray/AppData/Local/Programs/Python/Python38-32/libs/ -lpython38
INCLUDEPATH += C:/Users/Ray/AppData/Local/Programs/Python/Python38-32/include
helloPy.py文件内容:
# This Python file uses the following encoding: utf-8
# if__name__ == "__main__":
# pass
def hello():
print("hello,Python!")
main.cpp内容:
#include "mainwindow.h"
#include
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
//python模块
Py_Initialize();
if(!Py_IsInitialized())
{
return -1;
}
//执行单句Python语句,用于给出调用模块的路径,否则将无法找到相应的调用模块
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//获取helloPy.py模块的指针
PyObject* pModule = PyImport_ImportModule("helloPy");
if(!pModule)
{
std::cout<<"open failure"<<std::endl;
return -1;
}
//获取hello函数的指针
PyObject* pFunhello = PyObject_GetAttrString(pModule,"hello");
if(!pFunhello)
{
std::cout<<"get function hello failed"<<std::endl;
return -1;
}
//调用函数,传入参数为NULL
PyObject_CallFunction(pFunhello, NULL);
Py_Finalize();
w.show();
return a.exec();
}
假设你已经正确安装了Qt和python,由于Qt中的slots关键字与python重复,这里我们需要修改一下文件C:\Users\Ray\AppData\Local\Programs\Python\Python38-32\include\object.h(注意先将原文件备份):
原文件:
typedef struct{
const char* name;
int basicsize;
int itemsize;
unsigned int flags;
PyType_Slot *slots; /* terminated by slot==0. */
} PyType_Spec;
修改为:
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;
最关键的来了:要想在Qt中找到这个文件你必须要把他放在debug目录下也就是找到你的工程中你的项目自动生成的一个MingGW-DeBug(名字最长的那玩意)然后进入debug目录,把你的脚本放在里面。很坑,不过没办法。