#include <Python.h>
MyWindow::MyWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MyWindow), m_Model(NULL) { ui->setupUi(this); myCombo = new QComboBox(this); //...初始化combobox //绑定comboBoxchange事件 connect(myCombo, SIGNAL(currentIndexChanged(int)), SLOT(onComboChanged(int))); myWatcher = new QFutureWatcher<QString>(this); //监听任务结束事件 connect(myWatcher, SIGNAL(finished()), this, SLOT(onValueChanged())); ... } MyWindow::~MyWindow() { //销毁资源 myWatcher->cancel(); myWatcher->waitForFinished(); delete myWatcher; } void MyWindow::onComboChanged(int idx) { QString selectedValue = myCombo->currentData().value<QString>(); QFuture<QString> myFuture = QtConcurrent::run(MyWindow::callPython, selectedValue); cacWatcher->setFuture(myFuture); }
QString MyWindow::callPython(QString selectedValue){ QString result = ""; if(Py_IsInitialized() == 0){ Py_Initialize(); } QString filename = "py文件路径"; QFileInfo filepath = QFileInfo(filename); QString path = filepath.absolutePath(); PyObject *sys = PyImport_ImportModule("sys"); PyObject *syspath = PyObject_GetAttrString(sys, "path"); PyList_Insert(syspath, 0, PyString_FromFormat(path.toStdString().c_str())); filename = filepath.fileName().split(".")[0]; PyObject *pName = PyString_FromString(filename.toStdString().c_str()); PyObject *pModule = PyImport_Import(pName); if (pModule != NULL) { PyObject *pDict = PyModule_GetDict(pModule); PyObject *pFunc = PyDict_GetItem(pDict, PyString_FromString("函数名称")); if (pFunc != NULL) { PyObject *pyParams = PyTuple_New(2); PyTuple_SetItem(pyParams, 0, Py_BuildValue("s", selectedValue.toStdString().c_str()));
PyObject *pythonResult = PyObject_CallObject(pFunc, pyParams); result = QString(PyString_AsString(pythonResult).c_str());
} else { msgBox.setText("can't find function"); msgBox.exec(); } } else { msgBox.setText("can't find dir"); msgBox.exec(); } } catch (std::exception &err) { msgBox.setText(err.what()); msgBox.exec(); } return result;}
void MyWindow::onValueChanged() { this->myValue = myWatcher->result(); // ...业务代码 }
评论