Using QByteArray with C++ types
-
https://forum.qt.io/topic/66808/qt3d-draw-grid-axis-lines/3
I want to define custom shapes in Qt3D using PyQt5. In this examples there is a code like this:
QByteArray indexBytes; indexBytes.resize(2 * sizeof(unsigned int)); // start to end unsigned int *indices = reinterpret_cast<unsigned int*>(indexBytes.data()); *indices++ = 0; *indices++ = 1; auto *indexBuffer = new Qt3DRender::QBuffer(geometry); indexBuffer->setData(indexBytes);
I want to port this code to Python but I have no idea how to populate QByteArray with C++ types. If this is impossible is there a way to define custom mesh in PyQt3D?
-
@JonB Using
struct.pack
solved my problem. Here equivalent Python code:bufferBytes = QByteArray(struct.pack('6f', 0, 0, 0, 2, 2, 2))
compared C++ one:
QByteArray bufferBytes; bufferBytes.resize(3 * 2 * sizeof(float)); float *positions = reinterpret_cast<float*>(bufferBytes.data()); *positions++ = 0; *positions++ = 0; *positions++ = 0; *positions++ = 2; *positions++ = 2; *positions++ = 2;
-
@maydin
So this code creates an 8-byteQByteArray
, tells compiler to treat it as a pointer to a buffer ofunsigned int
s, and then pokes in two integers one after the other.If we ignore for the moment the question of integer storage byte-order, this looks similar-ish to
memcpy()
, so I Googledpython memcpy
(you might try others). This led me to https://stackoverflow.com/questions/13689628/is-there-a-python-equivalent-to-memcpy, and the accepted solution there. Untested, but I think they are saying you can go:indices[0:4] = 0 indices[4:8] = 1
This should certainly work if
indices = bytes(8)
. I don't know if you can do that against aQByteArray
. You can use a Pythonbytes
where you can use a QtQByteArray
, you'd have to check whether conversion does a copy of whether it can use the Pythonbytes
directly in theQByteArray
.I hope the above gets you going at least.
-
@JonB Using
struct.pack
solved my problem. Here equivalent Python code:bufferBytes = QByteArray(struct.pack('6f', 0, 0, 0, 2, 2, 2))
compared C++ one:
QByteArray bufferBytes; bufferBytes.resize(3 * 2 * sizeof(float)); float *positions = reinterpret_cast<float*>(bufferBytes.data()); *positions++ = 0; *positions++ = 0; *positions++ = 0; *positions++ = 2; *positions++ = 2; *positions++ = 2;
-
maydin thanks 👌