How to pass arrays from Python to Qt?

There are multiple ways to call Python in Qt and pass arrays. Two common methods are described below:

Option 1: Using QProcess to call a Python script.

QStringList arguments;
arguments << "your_python_script.py" << "arg1" << "arg2" << "...";

QProcess process;
process.start("python", arguments);
process.waitForFinished();

QString output = process.readAllStandardOutput();

In a Python script, you can access passed arguments through sys.argv, where argv[0] is the script path, and the following arguments are the elements in the passed array.

Option 1:
Second method: Call Python functions using PyQt’s QPythonCallable.

#include <QApplication>
#include <QAxScript>
#include <QAxObject>
#include <QDebug>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    QAxScript engine("Python");
    engine.setScript("your_python_script.py");
    engine.start();

    QAxObject* function = engine.globalObject().querySubObject("your_python_function_name");
    QVariantList arguments;
    // 将数组元素加入到arguments中
    arguments << QVariant(1) << QVariant(2) << QVariant(3);
    QVariant result = function->call(QVariant(arguments));
    qDebug() << result;

    engine.quit();

    return a.exec();
}

In a Python script, it is necessary to define a function that accepts an array as a callable object, for example:

def your_python_function_name(arg_list):
    # 处理数组
    return "result"

This method requires the use of QAxScript and adding QT += axcontainer in the .pro file.

There are two common methods to invoke Python and pass an array, choose the appropriate one based on the specific situation.

bannerAds