Returning arrays from Qt to Python
Dynamic Python binding for Qt Applications
Brought to you by:
florianlink,
marcusbarann
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:
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 :-(
So, what's the best way to get a 2D array from my Qt app into Python?
Jeff
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.
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!
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*.