pro调用python libs_QT应用(12)-QT调用python

功能:用qtcreator调用python文件。

1.环境:win10       64 位

python3.8 64位

mingw      64位

位数一定要匹配,如果是64位,全部为64位。包括环境变量中的设定值。

2.pro 配置

路径选择 自己盘上的安装路径

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../../ProgramData/Python/Python38/libs/ -lpython38

else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../../ProgramData/Python/Python38/libs/ -lpython38_d

INCLUDEPATH += $$PWD/../../ProgramData/Python/Python38/libs

DEPENDPATH += $$PWD/../../ProgramData/Python/Python38/libs

INCLUDEPATH += $$PWD/../../ProgramData/Python/Python38/include

DEPENDPATH += $$PWD/../../ProgramData/Python/Python38/include

#win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../../ProgramData/Python/Python38/libs/libpython38.a

#else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../../ProgramData/Python/Python38/libs/libpython38d.a

win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../../ProgramData/Python/Python38/libs/python38.lib

else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../../ProgramData/Python/Python38/libs/python38_d.lib

3.main.cpp

1 #include "qtpyprj.h"

2

3 #include

4 #include

5 #include

6 #include

7

8 int main(int argc, char *argv[])9 {10 QApplication a(argc, argv);11 qDebug()<

13 Py_SetPythonHome((const wchar_t *)(L"D:/ProgramData/Python/Python38"));14 //1.初始化Python解释器

15 Py_Initialize();16 if(!Py_IsInitialized())17 {18 qDebug()<

22 PyObject * pModule = PyImport_ImportModule("qtpyprj"); //pModule 调用的文件名,没有后缀

23 if (!pModule)24 {25 qDebug()<

29 //3.调用函数无参的

30 PyObject * pFunc_run = PyObject_GetAttrString(pModule, "run"); //pFunc 调用的函数名

31 if (!pFunc_run || !PyCallable_Check(pFunc_run))32 {33 qDebug()<

38 /*qDebug()<

46 //4. 函数调用是有两种,一种传参数的,一种不传参数的。47 //传参数有两种方法:48 //4.1.1创建方法149 PyObject *arg3 =PyTuple_New(2);50 PyObject *arg1 = PyLong_FromLong(1050);51 PyObject *arg2 = PyLong_FromLong(520);52

53 PyTuple_SetItem(arg3,0,arg1);54 PyTuple_SetItem(arg3,1,arg2);55

56 //4.1.2创建方法257 // PyObject *args3 =Py_BuildValue("",8.5,103.2);58 //4.2 调用python 的add函数59 PyObject *fe=PyEval_CallObject(pFunc_add, arg3); //pFunc 调用函数60 //4.3返回值处理61 float res2=0;62 PyArg_Parse(fe,"f",&res2);//是浮点数63

64 //4.4 输出结果65 qDebug()<

67 Py_Finalize(); //Py_Finalize 结束

68 return 0;69 }

4.python 文件存放目录

.py,.pyc与.exe3个文件同文件夹。

997dcd1f7a9aa785e5392293ff3f5a62.png

5.python文件

defrun():print("hello qt")defadd(a,b):return a+b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值