Struct to bytearray and vice versa?



  • I have the following structure. While drag and drop, I've to pass this struct to another widget. How can I do this?

    @struct ImageData {
    QString imageOption;
    QImage fullImage;
    QImage mirrorImage;
    QImage tileImage;
    QImage displayImage;
    int width;
    int height;
    };@



  • Hi,
    Qt: Make it a typedef, add the struct typedef to the Qt known variables list and (qRegisterMetaType() in the QMetaType class) past in signal/slot.
    Basic C++: Typedef the type and use as a function parameter.



  • so, code example accomplish this:

    @struct ImageData
    {
    ..
    };

    Q_DECLARE_METATYPE( ImageData) //Done in the same file as the struct definition@



  • This has to be handled using "QMimeData":http://qt-project.org/doc/qt-4.8/qmimedata.html . For more information about mime data and drag and drop have a look at this "article about drag and drop in Qt":http://qt-project.org/doc/qt-4.8/dnd.html#adding-new-drag-and-drop-types .
    If you still have questions after reading those docs please ask them.

    Edit: to convert your struct to/from a bytearray you can use "QDataStream":http://qt-project.org/doc/qt-4.8/qdatastream.html . QDataStream supports QImage, QString, int and many other types ( "here":http://qt-project.org/doc/qt-4.8/datastreamformat.html is a list of all supported types ).



  • I solved it using Qdatastream by appending each member of struct. But, isn't there anyway to pass the complete struct directly?


  • Moderators

    [quote author="Gowtam" date="1380514057"]I solved it using Qdatastream by appending each member of struct. But, isn't there anyway to pass the complete struct directly?[/quote]
    Who should know how to store the data beside you? The compiler can't do it without magic ;)
    Since the struct name may not be unique and also may change over versions you also may want to store a version number with your struct to be backwards compatible for example.
    You see that there can't be a auto feature such a "simple" task.



  • Within your program, indeed you can.

    A QByteArray can contain all the information you want. You could use it to pass it something like an index to a data structure that is accessible by everyone involved in the drag & drop operation, or you can use it to contain a quintptr. You cast a pointer to the struct instance to the quintptr, put it in your QByteArray, and on the other side of the D&D operation, you do it the other way around.

    I would not, within my own application, serialize a set of images into a QByteArray just to support D&D. That seems rather wastefull.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.