D
D
Dmitry Belyakin2014-06-09 15:14:22
Qt
Dmitry Belyakin, 2014-06-09 15:14:22

Qt: strange behavior of QByteArray::replace

Wrote this thread:

ba = new QByteArray(length,'\0');
lastPos = 0;

QNetworkReply *reply = manager->get(request);
connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(slotDownloadProgress(qint64,qint64)));

void Player::slotDownloadProgress(qint64 cur, qint64 tot)
{

    if(cur > 256000)
    {
                QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
                ba->replace(lastPos,reply->bytesAvailable(),reply->readAll());
                lastPos = cur+1;
                if (media->state() == Phonon::StoppedState)
                {
                    media->setCurrentSource(Phonon::MediaSource(buffer));
                    emit timeToPlay();
                }
    }
}

In this example, replace somehow works like insert . As a result, I get a QByteArray twice the size of the expected one, i.e. information is recorded during the loading process, but the zeros that I filled with QByteArray during initialization are not replaced, but remain at the end of the byte array.
I write a simple example:
#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QByteArray *ba = new QByteArray(100,'\0');
    qDebug() << ba->size();
    ba->replace(0,10,"1234567890");
    qDebug() << ba->size();
    return a.exec();
}

Of course it works the way it should.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel K, 2014-06-09
@nightvision

There is nothing strange.
You tell him how much to replace, but you didn't specify FOR HOW MUCH (the fourth parameter of the function) .
So he pushes the rest after replacing, while shifting what was.
Something like this:
Or if you need to leave what was in the original array, then specify the same value for the second and fourth parameters - how much to replace, i.e. reply->bytesAvailable()
Hope it works, but it's better to check the documentation.
The example works because the string is the same length as how much to replace, so there is nothing to cram.

D
Dmitry Belyakin, 2014-06-09
@nightvision

The variation from PavelK works, but the following also worked in my case:

qint64 available = reply->bytesAvailable();
                qDebug() << available;
                ba->replace(lastPos,available,reply->readAll());

those. first writing to a variable, and then passing it to a function. Weird but it worked
it is possible that the argument functions for
ba->replace(lastPos,reply->bytesAvailable(),reply->readAll());
are called starting from the last one.
So reply->bytesAvailable() is called after reply->readAll() and equals 0,
you changed the call order and everything worked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question