Qt调用Python脚本

Qt调用Python脚本

在调用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 <QApplication>
#include <Python.h>
#include <iostream>

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目录,把你的脚本放在里面。很坑,不过没办法。

运行:在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值