Menu

Returning arrays from Qt to Python

Help
Jeff S.
2013-01-17
2015-03-31
  • Jeff S.

    Jeff S. - 2013-01-17

    I would like to be able to return 2D arrays of double or int from within my Qt app to Python through PythonQt.
    or QVector<QVector<double>> would work too.

    I tried the 2nd option, registered the metatype with:

    qRegisterMetaType<QVector<QVector<int>>>("QVector<QVector<int>>");
    

    This works, sort of. Here's what I get from the python context when I try.
    The interface works, but I cannot get at the data :-(

    # from within the PythonQt  console
    py> ps = p1.positions()
    py> ps
    QVector<QVector<int> > (C++ object at: 0x00000000029C08D0)
    [i]#OK so far so good, I got the object[/i]
    py> ps[1]
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'QVector<QVector<int> >' object does not support indexing
    py> ps[1,1]
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'QVector<QVector<int> >' object has no attribute '__getitem__'
    

    So, what's the  best way to get a 2D array from my Qt app into Python?

    Jeff

     
  • Florian Link

    Florian Link - 2013-01-18

    Registering as a meta type allows PythonQt to recognize the object, but since QVector is not a QObject (and in your case it is even a nested template), there is no way for PythonQt to access the data.

    1. You can simple return a 1D array and interpret it as 2D (you can e.g. convert it to a NumPy ndarray in Python and change its layout).
    A 1D array can be returned as QVector<int/double> or QList<int/double> or QVariantList.

    2. You can either register a custom converter, see thread:

    https://sourceforge.net/projects/pythonqt/forums/forum/631392/topic/6555126

    3. You could return a Python array from your slot (PyObject*), e.g. link against numpy and return an ndarray that you generate in your code (we do that in MeVisLab).

    1. is the easiest, 2. is somewhat harder and both 2. and 3. requires quite some knowledge on how to initialize numpy as a C-Python extension and the Python C API.

     
  • gmas

    gmas - 2015-03-31

    Hi Florian, could you please expand a bit on points 2 and 3? A very basic working example converting a 2D array from C++ to numpy and back would be very useful!

     
  • Florian Link

    Florian Link - 2015-03-31

    For 3. you need to use the C Api of numpy to create an ndarray:

    http://docs.scipy.org/doc/numpy/reference/c-api.array.html

    You can use PyArray_New to create an array from existing data.
    I don't have code ready right now, if you google for the usage of the numpy api,
    You should find enough examples.

    An ndarray is just a PyObject, so you can return it from a slot using PyObject*.

     

Log in to post a comment.