QByteArray to QString

前端 未结 7 734
野性不改
野性不改 2020-12-13 18:13

I\'m having issues with QByteArray and QString.

I\'m reading a file and stores its information in a QByteArray. The file is in

相关标签:
7条回答
  • 2020-12-13 18:45

    Qt 4.8

    QString(byteArray).toStdString();
    

    Qt 5.12

    byteArray.toStdString();
    
    0 讨论(0)
  • 2020-12-13 18:46

    you can use QString::fromAscii()

    QByteArray data = entity->getData();
    QString s_data = QString::fromAscii(data.data());
    

    with data() returning a char*

    for QT5, you should use fromCString() instead, as fromAscii() is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872

    0 讨论(0)
  • 2020-12-13 18:49

    You can use QTextCodec to convert the bytearray to a string:

    QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);
    

    (1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

    From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

    0 讨论(0)
  • 2020-12-13 18:54

    You may find QString::fromUtf8() also useful.

    For QByteArray input of "\010" and "\000",

    QString::fromLocal8Bit(input, 1) returns "\010" and ""

    QString::fromUtf8(input, 1) correctly returns "\010" and "\000".

    0 讨论(0)
  • 2020-12-13 18:55

    You can use:

    QString::fromStdString(byteArray.toStdString())
    
    0 讨论(0)
  • 2020-12-13 18:57

    Use QString::fromUtf16((ushort *)Data.data()), as shown in the following code example:

    #include <QCoreApplication>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        // QByteArray to QString
        // =====================
    
        const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
        QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
        qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t
    
        QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
        qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]
    
        return a.exec();
    }
    

    This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.

    0 讨论(0)
提交回复
热议问题