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)

 

结果 

 #结束

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值