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

1、使用QT Creator 新建项目

2、添加Python解释器

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

bash 复制代码
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脚本编写

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 无参函数的调用

cpp 复制代码
#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 有参函数的调用

cpp 复制代码
#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 函数返回多个参数的调用

cpp 复制代码
#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

python 复制代码
#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

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

cpp 复制代码
#include "mainwindow.h"

#include <QApplication>

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

运行结果:

相关推荐
JouJz1 分钟前
Java虚拟机之垃圾收集(一)
java·开发语言·jvm
五行星辰32 分钟前
Java链接redis
java·开发语言·redis
邪恶的贝利亚33 分钟前
C++之序列容器(vector,list,dueqe)
开发语言·c++
原来是猿33 分钟前
蓝桥备赛(13)- 链表和 list(上)
开发语言·数据结构·c++·算法·链表·list
异常驯兽师35 分钟前
Java集合框架深度解析:List、Set与Map的核心区别与应用指南
java·开发语言·list
成功助力英语中国话38 分钟前
SDK编程,MFC编程,WTL编程之间的关系
c++·mfc
仟濹1 小时前
【算法 C/C++】二维差分
c语言·c++·算法
Ryan_Gosling2 小时前
QT-异步编程
开发语言·qt
Pocker_Spades_A2 小时前
Python刷题:Python基础
开发语言·python
总斯霖2 小时前
题解:士兵排列
数据结构·c++·算法