使用 QT 调用 Python 实现功能
下载pythonWelcome to Python.org
查看当前安装的python
切换一下python版本
打开环境变量
将想要的python版本提前
查询一下当前的python版本
python --version
QT端的修改
参数:%{CurrentDocument:FilePath}
工作目录:%{CurrentDocument:Path}
QT中新建一个python文件
python中编写代码
print("Hello World!")
QT代码调用python
在.pro文件中将python的include和lib包含进来
INCLUDEPATH += -I F:\Python38\include
LIBS += -LF:\Python38\libs -lpython38
在widget中添加避免python的slots冲突
#include <cmath>
#undef slots
#include <Python.h>
#define slots Q_SLOTS
widget中添加代码:
Py_Initialize();
if ( !Py_IsInitialized() )
{
qDebug("python 初始化失败!");
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.argv = ['python.py']");
PyRun_SimpleString("sys.path.append('./')");
//导入iqa.py模块
PyObject* pModule = PyImport_ImportModule("iqa");
if (!pModule)
{
qDebug("Cant open python file!\n");
}
PyObject* pFunhello= PyObject_GetAttrString(pModule,"myPrint");
if(!pFunhello)
{
qDebug()<<"Get function hello failed";
}
//调用temperImg函数
PyObject_CallFunction(pFunhello,"s","123");
//结束,释放python
Py_Finalize();
python代码
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
def myPrint(string):
print(string)
结果
#结束
作者:q_fy_p