首先要确保qt和python位数匹配,本人因为位数不同多花了一天的时间查问题结果发现是位数不同。
环境:win10 python3.8(64位) qt5.12.10(64位)
1. 新建一个QT项目
2. 在.pro文件中加入需要的python库文件目录
打开.pro文件,右键选择添加库→外部库→浏览库文件→选择python38.lib
注意红色方框位置不要选错
将导入的语句的最后一行删掉
3. 修改object.h文件
我的路径是 D:\ThePaK\Python3.8\include
添加红框中的代码
执行新创建的QT项目,生成debug文件,将要执行的python脚本放在debug文件夹中
Py_Module.py
def prin():
return "hello"
def add(a,b):
return a+b
mainwindow.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "D:\ThePaK\Python3.8\include\Python.h"
#include<iostream>
#include<QDebug>
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Py_SetPythonHome((const wchar_t *)(L"D:/ThePaK/Python3.8")); //这步很重要,没有它会在执行python脚本时,调用不了python已安装的库
Py_Initialize();
if( !Py_IsInitialized() )
qDebug()<<"初始化失败";
//导入sys模块设置模块地址
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//QString setSysPath = QString("sys.path.append('%1')").arg(QCoreApplication::applicationDirPath());
//PyRun_SimpleString(setSysPath.toStdString().c_str());
//创建模块指针
PyObject* pModule = PyImport_ImportModule("Py_Module");
if (!pModule)
qDebug()<<"获取模块指针失败";
//创建函数指针
PyObject* pFunc= PyObject_GetAttrString(pModule,"add");
PyObject* pFunc2= PyObject_GetAttrString(pModule,"prin");
if(!pFunc)
qDebug()<<"获取函数指针1失败";
if(!pFunc2)
qDebug()<<"获取函数指针2失败";
//无参函数
PyObject* pPara2 = PyObject_CallFunction(pFunc2, 0);
char* res3;
PyArg_Parse(pPara2, "s", &res3);
qDebug()<<"print(f):"<<res3;
//创建函数参数,方法1
PyObject* pPara = PyTuple_New(2); // 2个参数
PyTuple_SetItem(pPara, 0, Py_BuildValue("i",7)); //参数1为int型 1
PyTuple_SetItem(pPara, 1, Py_BuildValue("i",2)); //参数2为int型 2
//pPara = Py_BuildValue("(i,i)",1,2); //连写方式
/*
PyObject* pPara = PyTuple_New(2); // 2个参数
PyTuple_SetItem(pPara, 0, Py_BuildValue("s","Hello")); //参数1为String型 "Hello"
PyTuple_SetItem(pPara, 1, Py_BuildValue("s","World!")); //参数2为String型 "World!"
*/
//创建函数参数,方法2
PyObject* args = PyTuple_New(2); // 2个参数
PyObject* arg1 = PyLong_FromLong(4); // 参数一设为4
PyObject* arg2 = PyLong_FromLong(3); // 参数二设为3
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
//调用Python函数,传入元组参数pPara
PyObject *FuncBack = PyObject_CallObject(pFunc,args);
//PyObject_CallObject(pFunc,nullptr); //无参数调用
//FuncBack是返回值指针,转换获取返回值
int res = 0;
PyArg_Parse(FuncBack,"i",&res);
qDebug()<<"返回值: "<<res;
//调用结束,销毁
Py_Finalize();
}
MainWindow::~MainWindow()
{
delete ui;
}
请注意,代码中的此句:
Py_SetPythonHome((const wchar_t *)(L"D:/ThePaK/Python3.8"));
这步很重要,没有它会在执行python脚本时,调用不了python已安装的库
有问题欢迎交流~