"plain/text" encodedData and QDataStream to readable QString

  • I'd like to convert the following snippet to use "plain/text" mimetype without relying on QTextStream

    bool DragDropListModel::dropMimeData(const QMimeData *data,
    Qt::DropAction action, int row, int column, const QModelIndex &parent)
    QByteArray encodedData = data->data("application/vnd.text.list");
    QDataStream stream(&encodedData, QIODevice::ReadOnly);
    QStringList newItems;

    while (!stream.atEnd()) {
    QString text;
    stream >> text;
    newItems << text;

    I tried to apply what said at http://stackoverflow.com/questions/19814193/qt-parse-string-of-undefined-size-from-a-binary-data-stream

    char *ch;
    QFile file("file.dat");
    QDataStream in(&file);
    in >> ch;
    QString str(ch);

    and http://www.qtcentre.org/threads/696-QDataStream-reading-into-QString

    stream.setByteOrder( QDataStream::BigEndian);
    quint16 id;
    stream >> id; // First two bytes
    char* filename;
    stream >> filename; // String of undefined size
    QString file = QString::fromLatin1(filename);
    qDebug() << "output: " << file;
    newItems << file;
    delete[] filename; //cleanup

    but I am always getting an empty string or 0.
    I am reading that "The only disadvantage to using QDataStream (over QTextStream) is that the resulting file is binary (i.e., not human readable)."
    Is there no way to convert QDataStream of plain text to readable QString?

  • // drag&drop plain/text from outside the app is "abcdefg"

    @ while (!stream.atEnd()) {
    char* a;
    stream.readRawData(a, 7); // abcdefg length = 7
    QString string(a);
    qDebug() << "output " << string; // WORKING => abcdefg

    say I write the following code before the while loop:

    @ quint8 v;
    stream >> v;
    qDebug() << "output: " << v; // => 97 = "a"@

    which is equivalent to

    @ quint8 v;
    stream >> v;
    QString a;
    qDebug() << "output: " << static_cast<char>(v); // => "a"@

    and the while loops crashes:<br>
    error: Exception at 0x5dd02907, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance)

    my plain/text string doesn't seem to have length bytes at the beginning.
    I could run it as it is but I am wondering if I could determine the length of the string in advance.
    Whenever I try to read from the stream through the << operator, I can't simply reset it to the beginning.

Log in to reply

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