当前位置: 首页 > news >正文

QT中使用C++调用 python脚本

1、使用QT Creator 新建项目

2、添加Python解释器

在.pro 文件中添加python头文件与链接库

INCLUDEPATH += -I /usr/include/python3.8/
LIBS += -L /usr/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8

本文实验为ubuntu自带python3.8,虚拟环境中的python解释器运行python脚本未成功

3、Python脚本编写

import os
import sys
import matplotlib.pyplot as plt
import numpy as np

print(os.path.dirname(os.getcwd()))
print(sys.path.append(os.path.dirname(os.getcwd())))
def test_add():
    x = [0,1,2,3,4,5,6,7,8,9,10]
    y = [2.83, 9.53, 14.52, 21.57, 38.26, 53.92, 73.15, 101.56, 129.54, 169.75, 207.59]
    z = np.polyfit(x, y, 3)
    p = np.poly1d(z)
    y_pre = p(x)

    # 绘图
    plt.plot(x,y, '+')
    plt.plot(x,y_pre)
    # 显示
    plt.show()

def add(a, b):
    c = a + b
    print(f"{a}+{b}={c}")
    return (c,7.7)


# test_add()
# add(2, 3)

4、 mainwindow.cpp内容编写

4.1 无参函数的调用

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#undef slots
#include "Python.h"
#define slots

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    
    Py_Initialize();
    
    if(!Py_IsInitialized())
    {
        qDebug() << "init err";
    }
    
    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("print(os.getcwd())");
    PyRun_SimpleString("sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))");
    //PyRun_SimpleString("print(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(sys.path)");
    PyObject * pmodle = PyImport_ImportModule("pyplot");
    
    if(!pmodle)
    {
        qDebug() << "can not open the file";
    }
    PyObject * callback = PyObject_GetAttrString(pmodle, "test_add");
    PyObject * ret = PyObject_CallObject(callback, NULL);
    
    Py_Finalize();
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

 4.2 有参函数的调用

#include "mainwindow.h"
#include "ui_mainwindow.h"
#undef slots
#include <Python.h>
#define slots
#include <QDebug>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    Py_Initialize();
    if(!Py_IsInitialized())
    {
        qDebug() << "init err";
    }

    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");

    PyRun_SimpleString("sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(os.getcwd())");
    PyRun_SimpleString("print(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(sys.path)");
    PyObject * pmodule = PyImport_ImportModule("pyplot");

    if(!pmodule)
    {
        qDebug() << "can not open the file";
    }


    PyObject * callback = PyObject_GetAttrString(pmodule, "add");
    PyObject * args = PyTuple_New(2);
    // PyObject * arg1 = PyLong_FromLong(3);
    // PyObject * arg2 = PyLong_FromLong(6);

    PyObject * arg1 = PyFloat_FromDouble(3.3);
    PyObject * arg2 = PyFloat_FromDouble(6.6);

    PyTuple_SetItem(args, 0, arg1);
    PyTuple_SetItem(args, 1, arg2);

    PyObject * ret = PyObject_CallObject(callback, args);

    // long c_ret = PyLong_AsLong(ret);
    float c_ret = PyFloat_AsDouble(ret);

    qDebug() << "c_ret = " << c_ret;


    Py_Finalize();
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

 4.3 函数返回多个参数的调用

#include "mainwindow.h"
#include "ui_mainwindow.h"
#undef slots
#include <Python.h>
#define slots
#include <QDebug>
#include <QLineEdit>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    Py_Initialize();
    if(!Py_IsInitialized())
    {
        qDebug() << "init err";
    }

    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");

    PyRun_SimpleString("sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(os.getcwd())");
    PyRun_SimpleString("print(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(sys.path)");
    PyObject * pmodule = PyImport_ImportModule("pyplot");
    
    

    if(!pmodule)
    {
        qDebug() << "can not open the file";
    }


    PyObject * callback = PyObject_GetAttrString(pmodule, "add");
    PyObject * args = PyTuple_New(2);
    // PyObject * arg1 = PyLong_FromLong(3);
    // PyObject * arg2 = PyLong_FromLong(6);
    // 传入参数
    PyObject * arg1 = PyFloat_FromDouble(3.3);
    PyObject * arg2 = PyFloat_FromDouble(6.6);

    PyTuple_SetItem(args, 0, arg1);
    PyTuple_SetItem(args, 1, arg2);

    PyObject * ret = PyObject_CallObject(callback, args);

    // 传出参数
    // long c_ret = PyLong_AsLong(ret);
    // float c_ret = PyLong_AsLong(ret);
    // qDebug() << "c_ret = " << c_ret;

    double ret1, ret2;
    PyArg_ParseTuple(ret, "d|d", &ret1, &ret2);
    qDebug() << "ret1 = " << ret1 << " ret2 = " << ret2;

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    Py_Finalize();
    delete ui;
}

4.4  QT按键调用python函数

 4.4.1 mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#undef slots
#include <Python.h>
#define slots
#include <QDebug>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>


QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QLineEdit * A_par;
    QLineEdit * B_par;
    QLineEdit * C_par;
    QPushButton * func_btn;
    QGridLayout * Grid;
    PyObject * callback;
    PyObject * args;
    PyObject * arg1;
    PyObject * arg2;
    PyObject * ret;
    PyObject * pmodule;

private slots:
    void python_func();

};
#endif // MAINWINDOW_H

 4.4.2 mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Py_Initialize();
    if(Py_IsInitialized())
    {
        qDebug() << "init ok";
    }

    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");

    PyRun_SimpleString("sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(os.getcwd())");
    PyRun_SimpleString("print(os.path.dirname(os.path.dirname(os.getcwd())))");
    PyRun_SimpleString("print(sys.path)");
    pmodule = PyImport_ImportModule("pyplot");
    if(pmodule)
    {
        PyErr_Print();
        qDebug() << "file is ok";
    }
    callback = PyObject_GetAttrString(pmodule, "add");
    A_par = new QLineEdit();
    B_par = new QLineEdit();
    C_par = new QLineEdit();
    func_btn = new QPushButton("=");
    Grid = new QGridLayout();
    Grid->addWidget(A_par, 0, 1);
    Grid->addWidget(B_par, 0, 2);
    Grid->addWidget(C_par, 1, 1);
    Grid->addWidget(func_btn, 0, 3);
    this->centralWidget()->setLayout(Grid);
    connect(func_btn, SIGNAL(clicked()), this, SLOT(python_func()));

}

MainWindow::~MainWindow()
{
    Py_Finalize();
    delete ui;
}


void MainWindow::python_func()
{
    double A = A_par->text().toDouble();
    double B = B_par->text().toDouble();

    args = PyTuple_New(2);
    // PyObject * arg1 = PyLong_FromLong(3);
    // PyObject * arg2 = PyLong_FromLong(6);
    // 传入参数
    arg1 = PyFloat_FromDouble(A);
    arg2 = PyFloat_FromDouble(B);

    PyTuple_SetItem(args, 0, arg1);
    PyTuple_SetItem(args, 1, arg2);


   ret = PyObject_CallObject(callback, args);

    // 传出参数
    // long c_ret = PyLong_AsLong(ret);
    // float c_ret = PyLong_AsLong(ret);
    // qDebug() << "c_ret = " << c_ret;

    double ret1, ret2;
    PyArg_ParseTuple(ret, "d|d", &ret1, &ret2);
    qDebug() << "ret1 = " << ret1 << " ret2 = " << ret2;

    C_par->setText(QString::number(ret1));
}

 4.4.3 main.cpp 

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

 运行结果:

相关文章:

  • DeepSeek大模型 —— 全维度技术解析
  • 基于MD5分块哈希的前端图片重复检测方案
  • 系统运维分级掌握知识技能
  • 晶晨S905L3S/S905L3SB芯片烧录-BL(bootloader)加载工具分享
  • 外键 FK enable constraints enq:TM lock
  • ubuntu局域网部署stable-diffusion-webui记录
  • Java锁
  • AF3 curry1函数解读
  • 洛谷P1102 A-B 数对
  • 计算机组成原理---操作系统Linux
  • Mybatis 的关联映射(一对一,一对多,多对多)
  • 是德科技十周年:以创新丈量未来,用科技赋能世界
  • springboot项目使用中创InforSuiteAS替换tomcat
  • makefile新手入门教程
  • 【内网服务发布公网】
  • 《水利水电安全员考试各题型对比分析及应对攻略》
  • nftables 入门:简洁高效的 Linux 防火墙管理
  • 基于大型模实现的AiEditor
  • 数据结构与算法 计算机组成 八股
  • Aws batch task 无法拉取ECR 镜像unable to pull secrets or registry auth 问题排查
  • 金爵奖主竞赛单元评委名单公布,中国评委有黄渤、咏梅等人
  • 重庆一男大学生掉进化粪池死亡,重庆对外经贸学院:以学校通报为准
  • 安徽凤阳通报鼓楼瓦片脱落:2023年曾维修,已成立调查组
  • 广州某科技公司遭网络攻击,境外“黑手”被锁定
  • 俄需要达成怎样的特别军事行动结果?普京:包含四个方面
  • 外媒:哈马斯一名高级指挥官尸体被发现,系辛瓦尔弟弟