Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

QByteArray and QString

QString always contains UTF-16 encoded strings, but what if you have data in an unknown (yet) encoding? Also, what if the data is not even text? In these cases, Qt uses the QByteArray class. When you read data directly from a file or receive it from a network socket, Qt will return the data as a QByteArray, indicating that this is an arbitrary array of bytes without any information about the encoding:

QFile file("/path/to/file");
file.open(QFile::ReadOnly);
QByteArray array = file.readAll();

The closest equivalent of QByteArray in the standard library would be std::vector<char>. As the name implies, this is just an array of bytes with some helpful methods. In the preceding example, if you know that the file you read is in UTF-8, you can convert the data to a string, as follows:

QString text = QString::fromUtf8(array);

If you have no idea what encoding the file uses, it may be best to use the system encoding, so QString::fromLocal8Bit would be better. Similarly, when writing to a file, you need to convert the string to a byte array before passing it to the write() function:

QString text = "new file content\n";
QFile file("/path/to/file");
file.open(QFile::WriteOnly);
QByteArray array = text.toUtf8();
file.write(array);
You can use file.close() to close the file. QFile will also automatically close the file when deleted, so if your QFile object goes out of scope immediately after you've finished working with the file, there is no need for an explicit close() call.