c++qtqbytearray

QByteArray indexOf deprecated?


I'm using Qt 5.15.2, I have the following code:

    QByteArray arybytData = mpsckIncoming->readAll();
    bool blnHTTP = false;
    
    if ( arybytData.startsWith("GET / HTTP/") == true ) {
    //HTTP Request, probably from browser, jump to end of header
        const QString cstrHeaderTerminator("\r\n\r\n");
        int intHdrEnd;
        
        if ( (intHdrEnd = arybytData.indexOf(cstrHeaderTerminator)) == -1 ) {

The line using QByteArray::indexOf() has the text:

'indexOf' is deprecated: Use QString's toUtf8(), toLatin1() or toLocal8Bit()

I don't understand this since none of the suggested functions are anything like the function of QByteArrray::indexOf().

Should I just ignore it?

I'm using:

Qt Creator 4.14.0
Based on Qt 5.15.2 (Clang 11.0 (Apple), 64 bit)
Built on Dec 17 2020 07:57:30
From revision 909f74dc56

Solution

  • Only QByteArray::indexOf(const QString& str, int from) is deprecated. The other overloads are still available.

    What you're meant to do is to use QString::toUtf8(), QString::toLatin1() or QString::toLocal8Bit() to retrieve a QByteArray representing the QString which can then be passed to the non-deprecated overloads of QByteArray::indexOf().

    The reason for this is most likely that the QByteArray::indexOf() overload that accepts the QString does not know how to interpret the string from an encoding point of view. Therefore, you have to do the "conversion" explicitly. I didn't look into this so maybe there are other reasons for the deprecation of that function.

    Looking at the documentation of the deprecated function in question we learn that this used QString::toUtf8() internally, therefore you can adapt your code like this to get the same behavior:

    if ( (intHdrEnd = arybytData.indexOf(cstrHeaderTerminator.toUtf8())) == -1 ) {