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

How to convert QVector<QPainterPath> to QByteArray and convert it back?



  • Hi, I am writing a code that can safely serialise a QVector<QPainterPath> to QByteArray and deserialise. I am not sure how to do so but I write some code based on my knowledge on it. Also, I am wondering what is the difference between sending data in terms of QByteArray or QDatastream. Any help is very welcome :)

    /*Serialising the data*/
    QByteArray Sender::convertPathToByteArray()
    {
        QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(path.constData()),sizeof(QPainterPath)*path.size());
        return data;
    }
    


  • @Christina123 Use QDataStream:

    // QPainterPath to QByteArray
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);
    ds.setVersion(QDataStream::Qt_5_15);
    ds << path;
    qDebug() << ba;
    
    // QByteArray to QPainterPath
    QPainterPath path;
    QDataStream ds(ba);
    ds.setVersion(QDataStream::Qt_5_15);
    ds >> path;
    qDebug() << path;
    

    And knowing that QDataStream supports QVector then in your case the code doesn't change much:

    // QVector<QPainterPath> to QByteArray
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);
    ds.setVersion(QDataStream::Qt_5_15);
    ds << paths;
    qDebug() << ba;
    
    // QByteArray to QVector<QPainterPath>
    QVector<QPainterPath> paths;
    QDataStream ds(ba);
    ds.setVersion(QDataStream::Qt_5_15);
    ds >> paths;
    qDebug() << paths;
    


  • @Christina123 Use QDataStream:

    // QPainterPath to QByteArray
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);
    ds.setVersion(QDataStream::Qt_5_15);
    ds << path;
    qDebug() << ba;
    
    // QByteArray to QPainterPath
    QPainterPath path;
    QDataStream ds(ba);
    ds.setVersion(QDataStream::Qt_5_15);
    ds >> path;
    qDebug() << path;
    

    And knowing that QDataStream supports QVector then in your case the code doesn't change much:

    // QVector<QPainterPath> to QByteArray
    QByteArray ba;
    QDataStream ds(&ba, QIODevice::WriteOnly);
    ds.setVersion(QDataStream::Qt_5_15);
    ds << paths;
    qDebug() << ba;
    
    // QByteArray to QVector<QPainterPath>
    QVector<QPainterPath> paths;
    QDataStream ds(ba);
    ds.setVersion(QDataStream::Qt_5_15);
    ds >> paths;
    qDebug() << paths;
    

Log in to reply