Qt调用Python-源代码
SharpTrader0_01.pro
1 QT += core gui 2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 5 CONFIG += c++11 6 7 # You can make your code fail to compile if it uses deprecated APIs. 8 # In order to do so, uncomment the following line. 9 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 10 11 SOURCES += \ 12 QPython.cpp \ 13 main.cpp \ 14 mainwindow.cpp 15 16 HEADERS += \ 17 QPython.h \ 18 mainwindow.h 19 20 FORMS += \ 21 mainwindow.ui 22 23 24 INCLUDEPATH += C:/Users/Mcwhirr/AppData/Local/Programs/Python/Python37/include 25 26 LIBS += -LC:/Users/Mcwhirr/AppData/Local/Programs/Python/Python37/libs -lpython37 27 28 29 # Default rules for deployment. 30 qnx: target.path = /tmp/$${TARGET}/bin 31 else: unix:!android: target.path = /opt/$${TARGET}/bin 32 !isEmpty(target.path): INSTALLS += target
mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 #include <QProcess> 6 #include <QtDebug> 7 #include <QApplication> 8 #include "QPython.h" 9 10 QT_BEGIN_NAMESPACE 11 namespace Ui { class MainWindow; } 12 QT_END_NAMESPACE 13 14 class MainWindow : public QMainWindow 15 { 16 Q_OBJECT 17 18 public: 19 MainWindow(QWidget *parent = nullptr); 20 ~MainWindow(); 21 22 private slots: 23 void OnReadData(); 24 25 signals: 26 void readyReadStandardOutput(); 27 28 private: 29 Ui::MainWindow *ui; 30 QProcess *process1; 31 }; 32 #endif // MAINWINDOW_H
QPython.h
1 #ifndef QPYTHON_H 2 #define QPYTHON_H 3 4 #undef slots 5 #include <Python.h> 6 #define slots Q_SLOTS 7 #include <QObject> 8 #include <QVariant> 9 10 /** 11 * @className QPython 12 * @brief excute PY 13 * @author Mcwhirr 14 * @date 2022-1-8 15 **/ 16 17 class QPython 18 { 19 public: 20 explicit QPython(const char *module); 21 ~QPython(); 22 23 bool callPyFunc(const char *func,const QVariantList &args = QVariantList(),QVariant *backVar = nullptr); 24 private: 25 PyObject *m_pModule = nullptr; 26 }; 27 28 29 30 #endif // QPYTHON_H
main.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include <QCoreApplication> 4 #include <QApplication> 5 #include <QProcess> 6 #include <QDebug> 7 #include "QPython.h" 8 9 int main(int argc, char *argv[]) 10 { 11 QApplication a(argc, argv); 12 MainWindow w; 13 w.show(); 14 return a.exec(); 15 }
mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include "QPython.h" 4 #include <QProcess> 5 #include <QtDebug> 6 7 8 MainWindow::MainWindow(QWidget *parent) : 9 QMainWindow(parent), 10 ui(new Ui::MainWindow) 11 { 12 ui->setupUi(this); 13 14 QPython pyExcute("pyCon"); 15 QVariant var = 0; 16 QVariantList args = {1,5}; 17 bool rc = pyExcute.callPyFunc("add",args,&var); 18 QTextBrowser *textBrowser = new QTextBrowser; 19 ui->textBrowser->insertPlainText(var.toString()); 20 21 QStringList args1("F:/SharpTrader0_01/SharpTrader0_01/hello.py"); 22 23 QProcess process1; 24 // process1->start(); 25 // process1->waitForStarted(); 26 // process1->execute(QString("Python.exe"),args1); 27 28 process1.start("cmd.exe");//直接启动python程序,而不是通过bash 29 QByteArray Output = process1.readAllStandardOutput(); 30 QString str = "dir "; 31 const char *cstr = str.toLocal8Bit().constData(); 32 process1.write(cstr); 33 QString result = Output; 34 qDebug()<<result; 35 process1.waitForFinished(); 36 37 QStringList arguments; 38 arguments << "/c" << "python D:/ProjBach_0_1/HEXCvt.py"; 39 QProcess process(this); 40 process.start("cmd.exe", arguments); 41 42 43 44 process.waitForStarted(); 45 process.waitForFinished(); 46 QString strResult = QString::fromLocal8Bit(process.readAllStandardOutput()); 47 QTextBrowser *textBrowser1 = new QTextBrowser; 48 ui->textBrowser1->setText(strResult); 49 50 // connect(process1,SIGNAL(readyReadStandardOutput()),this,SLOT(OnReadData())); 51 } 52 53 void MainWindow::OnReadData(){ 54 //打印出输出 55 QByteArray Output = process1->readAllStandardOutput(); 56 QString result = Output; 57 QTextBrowser *textBrowser1 = new QTextBrowser; 58 ui->textBrowser1->setText(result); 59 60 } 61 62 MainWindow::~MainWindow() 63 { 64 delete ui; 65 }
QPython.cpp
1 #include "QPython.h" 2 #include <QVariant> 3 #include <QtDebug> 4 5 QPython::QPython(const char *module) 6 { 7 //设置py home 打包用 8 //char homePath[] = "python37; 9 //Py_SetPythonHome(homePath); 10 //进行初始化 11 Py_Initialize(); 12 13 PyRun_SimpleString("import sys"); 14 PyRun_SimpleString("sys.path.append('./')"); 15 16 //如果初始化失败 返回 17 if(!Py_IsInitialized()){ 18 qDebug()<<__FUNCTION__<<"fail"<<"py init fail"; 19 return; 20 } 21 22 //加载模块,模块名称为myModule,就是mymodule.py文件 23 m_pModule = PyImport_ImportModule(module); 24 25 } 26 27 QPython::~QPython() 28 { 29 Py_Finalize(); 30 } 31 32 bool QPython::callPyFunc(const char *func, const QVariantList &args, QVariant *backVar) 33 { 34 if(m_pModule == nullptr){ 35 qDebug() << __FUNCTION__ <<"Mcwhirr"<<"module is null"; 36 return false; 37 } 38 //加载函数greateFunc 39 PyObject *pFuncHello = PyObject_GetAttrString(m_pModule,func); 40 //如果失败则返回 41 if(!pFuncHello){ 42 qDebug() <<__FUNCTION__<<"Mcwhirr"<<"load function fail"; 43 return false; 44 } 45 46 PyObject* pArgs = PyTuple_New(args.size()); 47 for(int i = 0; i < args.size(); ++i){ 48 QVariant arg = args.at(i); 49 switch (arg.type()) { 50 case QVariant::String: 51 { 52 QString str = arg.toString( ); 53 std::string str2 = str.toStdString( ); 54 const char *ch = str2.c_str( ); 55 PyTuple_SetItem(pArgs,i , Py_BuildValue("s", ch)); 56 } 57 break; 58 case QVariant::Int: 59 PyTuple_SetItem(pArgs,i,Py_BuildValue("i",arg.toInt())); 60 break; 61 case QVariant::Double: 62 PyTuple_SetItem(pArgs,i,Py_BuildValue("d",arg.toDouble())); 63 break; 64 65 default: 66 break; 67 68 } 69 } 70 71 //调用函数 72 auto pReturn = PyObject_CallObject(pFuncHello,pArgs); 73 74 if(backVar){ 75 switch (backVar->type()) { 76 case QVariant::String: 77 { 78 char *s = nullptr; 79 PyArg_Parse(pReturn,"s",&s); 80 QString str(s); 81 *backVar = QVariant::fromValue(str); 82 } 83 break; 84 case QVariant::Int: 85 { 86 int nResult; 87 PyArg_Parse(pReturn,"i",&nResult); 88 *backVar = QVariant::fromValue(nResult); 89 } 90 break; 91 case QVariant::Double: 92 { 93 double dResult; 94 PyArg_Parse(pReturn,"d",&dResult); 95 *backVar = QVariant::fromValue(dResult); 96 } 97 break; 98 default: 99 break; 100 } 101 } 102 return pReturn !=nullptr; 103 }
浙公网安备 33010602011771号