Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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-byte QByteArray, tells compiler to treat it as a pointer to a buffer of unsigned ints, 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 Googled python 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 a QByteArray. You can use a Python bytes where you can use a Qt QByteArray, you'd have to check whether conversion does a copy of whether it can use the Python bytes directly in the QByteArray.

    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;
    

Log in to reply