Skip to content

PythonQt.QtCore.QByteArray

QByteArray

PythonQtInstanceWrapper object

Native bases: PythonQtInstanceWrapper

Supplemental documentation: Qt 5 reference:

Detailed Description

QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings. Using QByteArray is much more convenient than using const char *. Behind the scenes, it always ensures that the data is followed by a '\0' terminator, and uses implicit sharing (copy-on-write) to reduce memory usage and avoid needless copying of data.

In addition to QByteArray, Qt also provides the QString class to store string data. For most purposes, QString is the class you want to use. It stores 16-bit Unicode characters, making it easy to store non-ASCII/non-Latin-1 characters in your application. Furthermore, QString is used throughout in the Qt API. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g., with Qt for Embedded Linux).

One way to initialize a QByteArray is simply to pass a const char * to its constructor. For example, the following code creates a byte array of size 5 containing the data "Hello":

QByteArray ba("Hello");

Although the size() is 5, the byte array also maintains an extra '\0' character at the end so that if a function is used that asks for a pointer to the underlying data (e.g. a call to data()), the data pointed to is guaranteed to be '\0'-terminated.

QByteArray makes a deep copy of the const char * data, so you can modify it later without experiencing side effects. (If for performance reasons you don't want to take a deep copy of the character data, use QByteArray::fromRawData() instead.)

Another approach is to set the size of the array using resize() and to initialize the data byte per byte. QByteArray uses 0-based indexes, just like C++ arrays. To access the byte at a particular index position, you can use operator[](). On non-const byte arrays, operator[]() returns a reference to a byte that can be used on the left side of an assignment. For example:

QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;

For read-only access, an alternative syntax is to use at():

for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << Qt::endl;
}

at() can be faster than operator[](), because it never causes a deep copy to occur.

To extract many bytes at a time, use left(), right(), or mid().

A QByteArray can embed '\0' bytes. The size() function always returns the size of the whole array, including embedded '\0' bytes, but excluding the terminating '\0' added by QByteArray. For example:

QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.

If you want to obtain the length of the data up to and excluding the first '\0' character, call qstrlen() on the byte array.

After a call to resize(), newly allocated bytes have undefined values. To set all the bytes to a particular value, call fill().

To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the data. The pointer is guaranteed to remain valid until a non-const function is called on the QByteArray. It is also guaranteed that the data ends with a '\0' byte unless the QByteArray was created from a raw data. This '\0' byte is automatically provided by QByteArray and is not counted in size().

QByteArray provides the following basic functions for modifying the byte data: append(), prepend(), insert(), replace(), and remove(). For example:

QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"

The replace() and remove() functions' first two arguments are the position from which to start erasing and the number of bytes that should be erased.

When you append() data to a non-empty array, the array will be reallocated and the new data copied to it. You can avoid this behavior by calling reserve(), which preallocates a certain amount of memory. You can also call capacity() to find out how much memory QByteArray actually allocated. Data appended to an empty array is not copied.

A frequent requirement is to remove whitespace characters from a byte array ('\n', '\t', ' ', etc.). If you want to remove whitespace from both ends of a QByteArray, use trimmed(). If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the byte array, use simplified().

If you want to find all occurrences of a particular character or substring in a QByteArray, use indexOf() or lastIndexOf(). The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here's a typical loop that finds all occurrences of a particular substring:

QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << Qt::endl;
    ++j;
}

If you simply want to check whether a QByteArray contains a particular character or substring, use contains(). If you want to find out how many times a particular character or substring occurs in the byte array, use count(). If you want to replace all occurrences of a particular value with another, use one of the two-parameter replace() overloads.

QByteArrays can be compared using overloaded operators such as operator\<(), operator\<\=(), operator\=\=(), operator>\=(), and so on. The comparison is based exclusively on the numeric values of the characters and is very fast, but is not what a human would expect. QString::localeAwareCompare() is a better choice for sorting user-interface strings.

For historical reasons, QByteArray distinguishes between a null byte array and an empty byte array. A null byte array is a byte array that is initialized using QByteArray's default constructor or by passing (const char *)0 to the constructor. An empty byte array is any byte array with size 0. A null byte array is always empty, but an empty byte array isn't necessarily null:

QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false

All functions except isNull() treat null byte arrays the same as empty byte arrays. For example, data() returns a valid pointer (not nullptr) to a '\0' character for a byte array and QByteArray() compares equal to QByteArray(""). We recommend that you always use isEmpty() and avoid isNull().

Maximum size and out-of-memory conditions

The current version of QByteArray is limited to just under 2 GB (2^31 bytes) in size. The exact value is architecture-dependent, since it depends on the overhead required for managing the data block, but is no more than 32 bytes. Raw data blocks are also limited by the use of int type in the current version to 2 GB minus 1 byte.

In case memory allocation fails, QByteArray will throw a std::bad_alloc exception. Out of memory conditions in the Qt containers are the only case where Qt will throw exceptions.

Note that the operating system may impose further limits on applications holding a lot of allocated memory, especially large, contiguous blocks. Such considerations, the configuration of such behavior or any mitigation are outside the scope of the QByteArray API.

Notes on Locale

Number-String Conversions

Functions that perform conversions between numeric data types and strings are performed in the C locale, irrespective of the user's locale settings. Use QString to perform locale-aware conversions between numbers and strings.

8-bit Character Comparisons

In QByteArray, the notion of uppercase and lowercase and of which character is greater than or less than another character is done in the Latin-1 locale. This affects functions that support a case insensitive option or that compare or lowercase or uppercase their arguments. Case insensitive operations and comparisons will be accurate if both strings contain only Latin-1 characters. Functions that this affects include contains(), indexOf(), lastIndexOf(), operator\<(), operator\<\=(), operator>(), operator>\=(), isLower(), isUpper(), toLower() and toUpper().

This issue does not apply to QStrings since they represent characters using Unicode.

Source: https://doc.qt.io/archives/qt-5.15/qbytearray.html

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
Base64Encoding attribute Any
Base64Option attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
Base64Options attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
Base64UrlEncoding attribute Any
KeepTrailingEquals attribute Any
OmitTrailingEquals attribute Any
__init__ function (self, *args: Any, **kwargs: Any) -> None Native constructor; consult class documentation for supported overloads. (shared captured text)
append function (self, s: Any, len: Any) -> Any X.append(s, len) -> PythonQt.QtCore.QByteArray
at function (self, i: int) -> int X.at(i) -> int
capacity function (self) -> int X.capacity() -> int
cbegin function (self) -> str X.cbegin() -> int
cend function (self) -> str X.cend() -> int
chop function (self, n: int) -> None Removes n bytes from the end of the byte array.
className function (self, *args: Any, **kwargs: Any) -> Any Return the classname of the object (shared captured text)
clear function (self) -> None Clears the contents of the byte array and makes it null.
contains function (self, c: Any) -> bool X.contains(c) -> bool
count function (self, c: Any) -> int X.count(c) -> int
data function (self) -> str Returns a pointer to the data stored in the byte array.
delete function (self, *args: Any, **kwargs: Any) -> Any Deletes the C++ object (at your own risk, my friend!) (shared captured text)
endsWith function (self, c: Any) -> bool X.endsWith(c) -> bool
fill function (self, c: int, size: int) -> Any X.fill(c, size) -> PythonQt.QtCore.QByteArray
fromBase64 function (self, base64: Any, options: Any) -> Any X.fromBase64(base64, options) -> PythonQt.QtCore.QByteArray
fromHex function (self, hexEncoded: Any) -> Any X.fromHex(hexEncoded) -> PythonQt.QtCore.QByteArray
fromPercentEncoding function (self, pctEncoded: Any, percent: int) -> Any X.fromPercentEncoding(pctEncoded, percent) -> PythonQt.QtCore.QByteArray
help function (self, *args: Any, **kwargs: Any) -> Any Shows the help of available methods for this class (shared captured text)
indexOf function (self, *args: Any, **kwargs: Any) -> int X.indexOf(c, from) -> int
inherits function (self, *args: Any, **kwargs: Any) -> Any Returns if the class inherits or is of given type name (shared captured text)
insert function (self, i: int, s: Any, len: Any) -> Any X.insert(i, s, len) -> PythonQt.QtCore.QByteArray
isEmpty function (self) -> bool X.isEmpty() -> bool
isNull function (self) -> bool X.isNull() -> bool
isSharedWith function (self, other: Any) -> bool X.isSharedWith(other) -> bool
lastIndexOf function (self, *args: Any, **kwargs: Any) -> int X.lastIndexOf(c, from) -> int
left function (self, len: int) -> Any X.left(len) -> PythonQt.QtCore.QByteArray
leftJustified function (self, width: int, fill: int, truncate: bool) -> Any X.leftJustified(width, fill, truncate) -> PythonQt.QtCore.QByteArray
length function (self) -> int X.length() -> int
mid function (self, index: int, len: int) -> Any X.mid(index, len) -> PythonQt.QtCore.QByteArray
number function (self, arg__1: Any, f: Any, prec: Any) -> Any X.number(arg__1, f, prec) -> PythonQt.QtCore.QByteArray
operator_assign function (self, arg__1: Any) -> Any X.operator_assign(arg__1) -> PythonQt.QtCore.QByteArray
prepend function (self, s: Any, len: Any) -> Any X.prepend(s, len) -> PythonQt.QtCore.QByteArray
push_back function (self, a: Any) -> Any This function is provided for STL compatibility.
push_front function (self, a: Any) -> Any This function is provided for STL compatibility.
readFrom function (self, arg__1: Any) -> Any (shared captured text)
remove function (self, index: int, len: int) -> Any X.remove(index, len) -> PythonQt.QtCore.QByteArray
repeated function (self, times: int) -> Any X.repeated(times) -> PythonQt.QtCore.QByteArray
replace function (self, before: Any, bsize: Any, after: Any, asize: Any) -> Any X.replace(before, bsize, after, asize) -> PythonQt.QtCore.QByteArray
reserve function (self, size: int) -> None Attempts to allocate memory for at least size bytes.
resize function (self, size: int) -> None Sets the size of the byte array to size bytes.
right function (self, len: int) -> Any X.right(len) -> PythonQt.QtCore.QByteArray
rightJustified function (self, width: int, fill: int, truncate: bool) -> Any X.rightJustified(width, fill, truncate) -> PythonQt.QtCore.QByteArray
setNum function (self, arg__1: Any, f: Any, prec: Any) -> Any X.setNum(arg__1, f, prec) -> PythonQt.QtCore.QByteArray
setRawData function (self, a: str, n: int) -> Any X.setRawData(a, n) -> PythonQt.QtCore.QByteArray
simplified function (self) -> Any X.simplified() -> PythonQt.QtCore.QByteArray
size function (self) -> int X.size() -> int
split function (self, sep: int) -> Any Splits the byte array into subarrays wherever sep occurs, and returns the list of those arrays.
squeeze function (self) -> None Releases any memory not required to store the array's data.
startsWith function (self, c: Any) -> bool X.startsWith(c) -> bool
swap function (self, other: Any) -> None Swaps byte array other with this byte array.
toBase64 function (self, options: Any) -> Any X.toBase64(options) -> PythonQt.QtCore.QByteArray
toDouble function (self, ok: Any) -> float X.toDouble(ok) -> float
toFloat function (self, ok: Any) -> float X.toFloat(ok) -> float
toHex function (self) -> Any X.toHex() -> PythonQt.QtCore.QByteArray
toInt function (self, ok: Any, base: int) -> int X.toInt(ok, base) -> int
toLower function (self) -> Any X.toLower() -> PythonQt.QtCore.QByteArray
toPercentEncoding function (self, exclude: Any, include: Any, percent: int) -> Any X.toPercentEncoding(exclude, include, percent) -> PythonQt.QtCore.QByteArray
toUShort function (self, ok: Any, base: int) -> int X.toUShort(ok, base) -> int
toUpper function (self) -> Any X.toUpper() -> PythonQt.QtCore.QByteArray
trimmed function (self) -> Any X.trimmed() -> PythonQt.QtCore.QByteArray
truncate function (self, pos: int) -> None Truncates the byte array at index position pos.
writeTo function (self, arg__1: Any) -> Any (shared captured text)