Kraup Kywpz
Kraup Kywpz

Reputation: 43

QT QString from QDataStream

I'm working with a buffer and I'm trying to get a string from it, but isnt working...

Example:

*void myFunc(QDataStream& in)
{
    quint8 v;
    in >> v;
    // Ok, I caught v value successfuly
    QString s;
    in >> s;
    // Didnt work :<
}*

The string lenght is stored on 2 first bytes...

Thanks

Upvotes: 3

Views: 12256

Answers (2)

alexisdm
alexisdm

Reputation: 29896

If the string was not written as a QString, you need to read its length and content separately.

quint8 v;
in >> v;

quint16 length = 0;
in >> length;

// the string is probably utf8 or latin
QByteArray buffer(length, Qt::Uninitialized);

in.readRawData(buffer.data(), length); 
QString string(buffer);

You might have to change the endianness of the QDataStream with QDataStream::setByteOrder before reading the 16-bit length.

Upvotes: 2

Andreas Fester
Andreas Fester

Reputation: 36649

We should really see the writing code and how you create the QDataStream. I tried with the following sample, and in this case your function works very well:

#include <QCoreApplication>
#include <QDebug>
#include <QDataStream>
#include <QBuffer>

void myFunc(QDataStream& in)
{
    quint8 v;
    in >> v;
qDebug() << v;
    // Ok, I caught v value successfuly
    QString s;
    in >> s;
qDebug() << s;
    // Didnt work :<
}


int main(int argc, char ** argv) {
    QCoreApplication a(argc, argv);

    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);


    // write test data into the buffer
    QDataStream out(&buffer);
    quint8 ival = 42;
    QString sval = "Qt";
    out << ival;
    out << sval;

    // read back data
    buffer.seek(0);
    myFunc(out);

    return a.exec();
}

Output when executed:

$ ./App 
42 
"Qt" 

Upvotes: 0

Related Questions