QByteArray to QObject typecasting



  • It seemed a trivial problem but somehow I did not find an example of casting from QByteArray to a QObject. I have tried several ways like QObject *temp = qobject_cast<QObject *>(QByteArray) .


  • Qt Champions 2016

    @ddze
    Well, you can't! These classes are not in the same hierarchy, so neither qobject_cast, nor dynamic_cast will work. In fact QByteArray is a base class, and doesn't depend on the Qt's meta-object system in comparison to QObject.

    Kind regards.



  • I thought so , thanks kshegunov. Looks like that I will have to overload the operators << and >>.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    In addition to what @kshegunov wrote. What are you trying to serialize exactly ?



  • @SGaist

    I am trying to serialize an object to into the QMimeData instance. Still need to get around the the missing operators << >> in the QGraphicsItem class.


  • Lifetime Qt Champion

    What would you like to do with that object ?



  • Transfer it from one place to another.


  • Qt Champions 2016

    @ddze
    Usually you don't do that, for the same reason that you don't copy QObject instances. If you have some data put into a QObject one usually extracts that data by a method and serializes the data itself, not the QObject. Consider what you're supposed to do to serialize the object hierarchy (with the parents and children) for a QObject instance? Also signals, slots and connections can't be trivially expanded in means of serialization ... there are tons of problems that prevent you from actually copying/serializing (which is basically the same thing) a QObject instance.

    Kind regards.



  • @kshegunov and @SGaist ,

    Thank you.

    I will probably go with the plan of storing a pointer into the QMimeData instead of streaming in/out the entire structure of the object.



  • Your class must implement this operators:

    QDataStream &operator<<
    QDataStream &operator>>
    

    After that you can use this code:

    MyClass c;
    QDataStream reader(byteArray);
    reader << c;
    


  • @Hamed.Masafi

    I know that and it would be easy if there was no a pointer to a QGraphicItem in the object structure (which has no << , >> ) operators.

    Also , my class provides the insertion and retraction operators but seems impossible to use them in the MIme as they fail to populate the members of the class such as QByteArray , QGraphicItem ... since these classes do not provide <<>> operators on their own.

    Looks pretty limited staff that can be transferred with the QMimeData , basic texts, urls, qt-class objects , but the objects from non Qt classes containing the Qt class members with no << >> operators, it is hard or even impossible - since it is requirement that they have << >> in order to use the QDataStream object.


Log in to reply
 

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