c++qtqtscript

Manipulate a 2d array from QtScript


I would like a way to be able to access an array of integers that is created somewhere in my main app from a QtScript, and after doing whatever manipulations that the script might perform return it back again.

What I am able to work until now is single values (e.g. an integer or boolean) and I have not seen an example on what I am describing.

Is there a way of doing that, or I will have to read the data one by one?


Solution

  • You can try encapusulating your 2d array in a QObject class, as indicated here: http://doc.qt.io/qt-5/qtscript-index.html and add some methods to manipuate it.

    Something like that (didn't test the code, so can contain some errors and is pretty raw)

    class MyArray: public QObject {
        int** m_array;
        public:
        Q_OBJECT
        MyArray(signed int x, signed int y) {
            m_array = new MyArray[x][y];
        }
        ~MyArray() { delete m_array; }
    
        Q_INVOKABLE int at(signed int x, signed int y) {
            if (m_array) return m_array[x][y];
        }
        ...
    }
    

    Than assign it to a QtScript property:

    MyArray *array2d = new MyArray(10, 5);
    QScriptValue arrayValue = engine.newQObject(array2d);
    engine.globalObject().setProperty("array2d", arrayValue);