- class QByteArray#
The
QByteArray
class provides an array of bytes. More…Synopsis#
Methods#
def
__init__()
def
__getitem__()
def
__len__()
def
__mgetitem__()
def
__msetitem__()
def
__reduce__()
def
__repr__()
def
__setitem__()
def
__str__()
def
append()
def
assign()
def
at()
def
back()
def
capacity()
def
cbegin()
def
cend()
def
chop()
def
chopped()
def
clear()
def
compare()
def
contains()
def
count()
def
data()
def
endsWith()
def
erase()
def
fill()
def
first()
def
front()
def
indexOf()
def
insert()
def
isEmpty()
def
isLower()
def
isNull()
def
isSharedWith()
def
isUpper()
def
isValidUtf8()
def
last()
def
lastIndexOf()
def
left()
def
leftJustified()
def
length()
def
mid()
def
__ne__()
def
__add__()
def
__iadd__()
def
__lt__()
def
__le__()
def
__eq__()
def
__gt__()
def
__ge__()
def
operator[]()
def
percentDecoded()
def
prepend()
def
push_back()
def
push_front()
def
remove()
def
removeAt()
def
removeFirst()
def
removeLast()
def
repeated()
def
replace()
def
reserve()
def
resize()
def
right()
def
rightJustified()
def
setNum()
def
setRawData()
def
shrink_to_fit()
def
simplified()
def
size()
def
sliced()
def
split()
def
squeeze()
def
startsWith()
def
swap()
def
toBase64()
def
toDouble()
def
toFloat()
def
toHex()
def
toInt()
def
toLong()
def
toLongLong()
def
toLower()
def
toShort()
def
toStdString()
def
toUInt()
def
toULong()
def
toULongLong()
def
toUShort()
def
toUpper()
def
trimmed()
def
truncate()
Static functions#
def
fromBase64()
def
fromHex()
def
fromRawData()
def
fromStdString()
def
number()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description#
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QByteArray
can be used to store both raw bytes (including ‘\0’s) and traditional 8-bit ‘\0’-terminated strings. UsingQByteArray
is much more convenient than usingconst 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 theQString
class to store string data. For most purposes,QString
is the class you want to use. It understands its content as Unicode text (encoded using UTF-16) whereQByteArray
aims to avoid assumptions about the encoding or semantics of the bytes it stores (aside from a few legacy cases where it uses ASCII). Furthermore,QString
is used throughout in the Qt API. The two main cases whereQByteArray
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 aconst char *
to its constructor. For example, the following code creates a byte array of size 5 containing the data “Hello”:ba = QByteArray("Hello")
Although the
size()
is 5, the byte array also maintains an extra ‘\0’ byte at the end so that if a function is used that asks for a pointer to the underlying data (e.g. a call todata()
), the data pointed to is guaranteed to be ‘\0’-terminated.QByteArray
makes a deep copy of theconst char *
data, so you can modify it later without experiencing side effects. (If, for example for performance reasons, you don’t want to take a deep copy of the data, usefromRawData()
instead.)Another approach is to set the size of the array using
resize()
and to initialize the data byte by 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:ba = QByteArray() 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 i in range(0, ba.size()): if ba.at(i) >= 'a' and ba.at(i) <= 'f': print("Found character in range [a-f]")
at()
can be faster than operator[](), because it never causes a deep copy to occur.To extract many bytes at a time, use
first()
,last()
, orsliced()
.A
QByteArray
can embed ‘\0’ bytes. Thesize()
function always returns the size of the whole array, including embedded ‘\0’ bytes, but excluding the terminating ‘\0’ added byQByteArray
. For example:ba1 = QByteArray("ca\0r\0t") ba1.size() # Returns 2. ba1.constData() # Returns "ca" with terminating \0. ba2 = QByteArray("ca\0r\0t", 3) ba2.size() # Returns 3. ba2.constData() # Returns "ca\0" with terminating \0. ba3 = QByteArray("ca\0r\0t", 4) ba3.size() # Returns 4. ba3.constData() # Returns "ca\0r" with terminating \0. cart = {'c', 'a', '\0', 'r', '\0', 't'} ba4 = QByteArray(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’ byte, 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, callfill()
.To obtain a pointer to the actual bytes, call
data()
orconstData()
. 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 theQByteArray
. It is also guaranteed that the data ends with a ‘\0’ byte unless theQByteArray
was created fromraw data
. This ‘\0’ byte is automatically provided byQByteArray
and is not counted insize()
.QByteArray
provides the following basic functions for modifying the byte data:append()
,prepend()
,insert()
,replace()
, andremove()
. For example:x = QByteArray("and") x.prepend("rock ") # x == "rock and" x.append(" roll") # x == "rock and roll" x.replace(5, 3, "") # x == "rock roll"
In the above example the
replace()
function’s first two arguments are the position from which to start replacing and the number of bytes that should be replaced.When data-modifying functions increase the size of the array, they may lead to reallocation of memory for the
QByteArray
object. When this happens,QByteArray
expands by more than it immediately needs so as to have space for further expansion without reallocation until the size of the array has greatly increased.The
insert()
,remove()
and, when replacing a sub-array with one of different size,replace()
functions can be slow ( linear time ) for large arrays, because they require moving many bytes in the array by at least one position in memory.If you are building a
QByteArray
gradually and know in advance approximately how many bytes theQByteArray
will contain, you can callreserve()
, askingQByteArray
to preallocate a certain amount of memory. You can also callcapacity()
to find out how much memory theQByteArray
actually has allocated.Note that using non-const operators and functions can cause
QByteArray
to do a deep copy of the data, due to implicit sharing .QByteArray
provides STL-style iterators (const_iterator
anditerator
). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.Note
Iterators and references to individual
QByteArray
elements are subject to stability issues. They are often invalidated when aQByteArray
-modifying operation (e.g.insert()
orremove()
) is called. When stability and iterator-like functionality is required, you should use indexes instead of iterators as they are not tied toQByteArray
‘s internal state and thus do not get invalidated.Note
Iterators over a
QByteArray
, and references to individual bytes within one, cannot be relied on to remain valid when any non-const method of theQByteArray
is called. Accessing such an iterator or reference after the call to a non-const method leads to undefined behavior. When stability for iterator-like functionality is required, you should use indexes instead of iterators as they are not tied toQByteArray
‘s internal state and thus do not get invalidated.If you want to find all occurrences of a particular byte or sequence of bytes in a
QByteArray
, useindexOf()
orlastIndexOf()
. The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the byte sequence if they find it; otherwise, they return -1. For example, here’s a typical loop that finds all occurrences of a particular string:ba = QByteArray("We must be , very ") j = 0 while (j = ba.indexOf("<b>", j)) != -1: print("Found <b> tag at index position ", j) j = j + 1
If you simply want to check whether a
QByteArray
contains a particular byte sequence, usecontains()
. If you want to find out how many times a particular byte sequence 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-parameterreplace()
overloads.QByteArray
s 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 bytes and is very fast, but is not what a human would expect.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 usingQByteArray
‘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’ byte for a null byte array andQByteArray()
compares equal toQByteArray
(“”). We recommend that you always useisEmpty()
and avoidisNull()
.Maximum size and out-of-memory conditions#
The maximum size of
QByteArray
depends on the architecture. Most 64-bit systems can allocate more than 2 GB of memory, with a typical limit of 2^63 bytes. The actual value also depends on the overhead required for managing the data block. As a result, you can expect the maximum size of 2 GB minus overhead on 32-bit platforms, and 2^63 bytes minus overhead on 64-bit platforms. The number of elements that can be stored in aQByteArray
is this maximum size.When memory allocation fails,
QByteArray
throws astd::bad_alloc
exception if the application is being compiled with exception support. Out of memory conditions in Qt containers are the only case where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.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.C locale and ASCII functions#
QByteArray
generally handles data as bytes, without presuming any semantics; where it does presume semantics, it uses the C locale and ASCII encoding. Standard Unicode encodings are supported byQString
, other encodings may be supported usingQStringEncoder
andQStringDecoder
to convert to Unicode. For locale-specific interpretation of text, useQLocale
orQString
.C Strings#
Traditional C strings, also known as ‘\0’-terminated strings, are sequences of bytes, specified by a start-point and implicitly including each byte up to, but not including, the first ‘\0’ byte thereafter. Methods that accept such a pointer, without a length, will interpret it as this sequence of bytes. Such a sequence, by construction, cannot contain a ‘\0’ byte.
Other overloads accept a start-pointer and a byte-count; these use the given number of bytes, following the start address, regardless of whether any of them happen to be ‘\0’ bytes. In some cases, where there is no overload taking only a pointer, passing a length of -1 will cause the method to use the offset of the first ‘\0’ byte after the pointer as the length; a length of -1 should only be passed if the method explicitly says it does this (in which case it is typically a default argument).
Spacing Characters#
A frequent requirement is to remove spacing characters from a byte array (
'\n'
,'\t'
,' '
, etc.). If you want to remove spacing from both ends of aQByteArray
, usetrimmed()
. If you want to also replace each run of spacing characters with a single space character within the byte array, usesimplified()
. Only ASCII spacing characters are recognized for these purposes.Number-String Conversions#
Functions that perform conversions between numeric data types and string representations are performed in the C locale, regardless of the user’s locale settings. Use
QLocale
to perform locale-aware conversions between numbers and strings.Character Case#
In
QByteArray
, the notion of uppercase and lowercase and of case-independent comparison is limited to ASCII. Non-ASCII characters are treated as caseless, since their case depends on encoding. This affects functions that support a case insensitive option or that change the case of their arguments. Functions that this affects includecompare()
,isLower()
,isUpper()
,toLower()
andtoUpper()
.This issue does not apply to
QString
s since they represent characters using Unicode.See also
QByteArrayView
QString
QBitArray
- class Base64Option#
(inherits
enum.Flag
) This enum contains the options available for encoding and decoding Base64. Base64 is defined by RFC 4648, with the following options:Constant
Description
QByteArray.Base64Encoding
(default) The regular Base64 alphabet, called simply “base64”
QByteArray.Base64UrlEncoding
An alternate alphabet, called “base64url”, which replaces two characters in the alphabet to be more friendly to URLs.
QByteArray.KeepTrailingEquals
(default) Keeps the trailing padding equal signs at the end of the encoded data, so the data is always a size multiple of four.
QByteArray.OmitTrailingEquals
Omits adding the padding equal signs at the end of the encoded data.
QByteArray.IgnoreBase64DecodingErrors
When decoding Base64-encoded data, ignores errors in the input; invalid characters are simply skipped. This enum value has been added in Qt 5.15.
QByteArray.AbortOnBase64DecodingErrors
When decoding Base64-encoded data, stops at the first decoding error. This enum value has been added in Qt 5.15.
fromBase64Encoding()
andfromBase64()
ignore the KeepTrailingEquals and OmitTrailingEquals options. If the IgnoreBase64DecodingErrors option is specified, they will not flag errors in case trailing equal signs are missing or if there are too many of them. If instead the AbortOnBase64DecodingErrors is specified, then the input must either have no padding or have the correct amount of equal signs.
- class Base64DecodingStatus#
- __init__(arg__1)#
- Parameters:
arg__1 –
PyByteArray
- __init__()
Constructs an empty byte array.
See also
- __init__(size, c)
- Parameters:
size – int
c – int
Constructs a byte array of size
size
with every byte set toch
.See also
- __init__(arg__1[, size=-1])
- Parameters:
arg__1 – str
size – int
Constructs a byte array containing the first
size
bytes of arraydata
.If
data
is 0, a null byte array is constructed.If
size
is negative,data
is assumed to point to a ‘\0’-terminated string and its length is determined dynamically.QByteArray
makes a deep copy of the string data.See also
- __init__(arg__1)
- Parameters:
arg__1 –
PyBytes
- __init__(arg__1)
- Parameters:
arg__1 –
QByteArray
Constructs a copy of
other
.This operation takes constant time , because
QByteArray
is implicitly shared . This makes returning aQByteArray
from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), taking linear time .See also
operator=()
- __getitem__()#
- __len__()#
- __mgetitem__()#
- __msetitem__()#
- __reduce__()#
- Return type:
object
- __repr__()#
- Return type:
object
- __setitem__()#
- __str__()#
- Return type:
object
- append(s, len)#
- Parameters:
s – str
len – int
- Return type:
This is an overloaded function.
Appends the first
len
bytes starting atstr
to this byte array and returns a reference to this byte array. The bytes appended may include ‘\0’ bytes.If
len
is negative,str
will be assumed to be a ‘\0’-terminated string and the length to be copied will be determined automatically usingqstrlen()
.If
len
is zero orstr
is null, nothing is appended to the byte array. Ensure thatlen
is not longer thanstr
.- append(count, c)
- Parameters:
count – int
c – int
- Return type:
This is an overloaded function.
Appends
count
copies of bytech
to this byte array and returns a reference to this byte array.If
count
is negative or zero nothing is appended to the byte array.- append(a)
- Parameters:
a –
QByteArray
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Appends the byte array
ba
onto the end of this byte array.Example:
x = QByteArray("free") y = QByteArray("dom") x.append(y) # x == "freedom"
This is the same as insert(
size()
,ba
).Note:
QByteArray
is an implicitly shared class. Consequently, if you append to an empty byte array, then the byte array will just share the data held inba
. In this case, no copying of data is done, taking constant time . If a shared instance is modified, it will be copied (copy-on-write), taking linear time .If the byte array being appended to is not empty, a deep copy of the data is performed, taking linear time .
The append() function is typically very fast ( constant time ), because
QByteArray
preallocates extra space at the end of the data, so it can grow without reallocating the entire array each time.- append(c)
- Parameters:
c – int
- Return type:
This is an overloaded function.
Appends the byte
ch
to this byte array.- append(a)
- Parameters:
a –
QByteArrayView
- Return type:
This is an overloaded function.
Appends
data
to this byte array.- assign(v)#
- Parameters:
v –
QByteArrayView
- Return type:
Replaces the contents of this byte array with a copy of
v
and returns a reference to this byte array.The size of this byte array will be equal to the size of
v
.This function only allocates memory if the size of
v
exceeds the capacity of this byte array or this byte array is shared.- assign(n, c)
- Parameters:
n – int
c – int
- Return type:
Replaces the contents of this byte array with
n
copies ofc
and returns a reference to this byte array.The size of this byte array will be equal to
n
, which has to be non-negative.This function will only allocate memory if
n
exceeds the capacity of this byte array or this byte array is shared.See also
- at(i)#
- Parameters:
i – int
- Return type:
int
Returns the byte at index position
i
in the byte array.i
must be a valid index position in the byte array (i.e., 0 <=i
<size()
).See also
operator[]()
- back()#
- Return type:
int
Returns the last byte in the byte array. Same as
at(size() - 1)
.This function is provided for STL compatibility.
Warning
Calling this function on an empty byte array constitutes undefined behavior.
- capacity()#
- Return type:
int
Returns the maximum number of bytes that can be stored in the byte array without forcing a reallocation.
The sole purpose of this function is to provide a means of fine tuning
QByteArray
‘s memory usage. In general, you will rarely ever need to call this function. If you want to know how many bytes are in the byte array, callsize()
.Note
a statically allocated byte array will report a capacity of 0, even if it’s not empty.
Note
The free space position in the allocated memory block is undefined. In other words, one should not assume that the free memory is always located after the initialized elements.
- cbegin()#
- Return type:
str
Returns a const STL-style iterator pointing to the first byte in the byte-array.
Warning
The returned iterator is invalidated on detachment or when the
QByteArray
is modified.See also
begin()
cend()
- cend()#
- Return type:
str
Returns a const STL-style iterator pointing just after the last byte in the byte-array.
Warning
The returned iterator is invalidated on detachment or when the
QByteArray
is modified.See also
cbegin()
end()
- chop(n)#
- Parameters:
n – int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Removes
n
bytes from the end of the byte array.If
n
is greater thansize()
, the result is an empty byte array.Example:
ba = QByteArray("STARTTLS\r\n") ba.chop(2) # ba == "STARTTLS"
See also
- chopped(len)#
- Parameters:
len – int
- Return type:
- clear()#
Clears the contents of the byte array and makes it null.
- compare(a[, cs=Qt.CaseSensitive])#
- Parameters:
a –
QByteArrayView
cs –
CaseSensitivity
- Return type:
int
Returns an integer less than, equal to, or greater than zero depending on whether this
QByteArray
sorts before, at the same position as, or after theQByteArrayView
bv
. The comparison is performed according to case sensitivitycs
.See also
operator==
Character Case
- contains(bv)#
- Parameters:
bv –
QByteArrayView
- Return type:
bool
Returns
true
if this byte array contains an occurrence of the sequence of bytes viewed bybv
; otherwise returnsfalse
.- contains(c)
- Parameters:
c – int
- Return type:
bool
This is an overloaded function.
Returns
true
if the byte array contains the bytech
; otherwise returnsfalse
.- count()#
- Return type:
int
Note
This function is deprecated.
Use
size()
orlength()
instead.This is an overloaded function.
Same as
size()
.- count(bv)
- Parameters:
bv –
QByteArrayView
- Return type:
int
Returns the number of (potentially overlapping) occurrences of the sequence of bytes viewed by
bv
in this byte array.See also
- count(c)
- Parameters:
c – int
- Return type:
int
This is an overloaded function.
Returns the number of occurrences of byte
ch
in the byte array.See also
- data()#
- Return type:
str
This is an overloaded function.
- endsWith(bv)#
- Parameters:
bv –
QByteArrayView
- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns
true
if this byte array ends with the sequence of bytes viewed bybv
; otherwise returnsfalse
.Example:
url = QByteArray("http://qt-project.org/doc/qt-5.0/qtdoc/index.html") if url.endsWith(".html"): ...
See also
- endsWith(c)
- Parameters:
c – int
- Return type:
bool
This is an overloaded function.
Returns
true
if this byte array ends with bytech
; otherwise returnsfalse
.- erase(first, last)#
- Parameters:
first – str
last – str
- Return type:
char
- erase(it)
- Parameters:
it – str
- Return type:
char
Removes the character denoted by
it
from the byte array. Returns an iterator to the character immediately after the erased character.QByteArray ba = "abcdefg"; auto it = ba.erase(ba.cbegin()); // ba is now "bcdefg" and it points to "b"
- fill(c[, size=-1])#
- Parameters:
c – int
size – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Sets every byte in the byte array to
ch
. Ifsize
is different from -1 (the default), the byte array is resized to sizesize
beforehand.Example:
ba = QByteArray("Istambul") ba.fill('o') # ba == "oooooooo" ba.fill('X', 2) # ba == "XX"
See also
- first(n)#
- Parameters:
n – int
- Return type:
- static fromBase64(base64[, options=QByteArray.Base64Option.Base64Encoding])#
- Parameters:
base64 –
QByteArray
options – Combination of
Base64Option
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a decoded copy of the Base64 array
base64
, using the options defined byoptions
. Ifoptions
containsIgnoreBase64DecodingErrors
(the default), the input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters. Ifoptions
containsAbortOnBase64DecodingErrors
, then decoding will stop at the first invalid character.For example:
text = QByteArray.fromBase64("UXQgaXMgZ3JlYXQh") text.data() # returns "Qt is great!" QByteArray.fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray.Base64Encoding) # returns "<p>Hello?</p>" QByteArray.fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray.Base64UrlEncoding) # returns "<p>Hello?</p>"
The algorithm used to decode Base64-encoded data is defined in RFC 4648.
Returns the decoded data, or, if the
AbortOnBase64DecodingErrors
option was passed and the input data was invalid, an empty byte array.- static fromBase64Encoding(base64[, options=QByteArray.Base64Option.Base64Encoding])#
- Parameters:
base64 –
QByteArray
options – Combination of
Base64Option
- Return type:
FromBase64Result
- static fromHex(hexEncoded)#
- Parameters:
hexEncoded –
QByteArray
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a decoded copy of the hex encoded array
hexEncoded
. Input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters.For example:
text = QByteArray.fromHex("517420697320677265617421") text.data() # returns "Qt is great!"
See also
- static fromPercentEncoding(pctEncoded[, percent='%'])#
- Parameters:
pctEncoded –
QByteArray
percent – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Decodes
input
from URI/URL-style percent-encoding.Returns a byte array containing the decoded text. The
percent
parameter allows use of a different character than ‘%’ (for instance, ‘_’ or ‘=’) as the escape character. Equivalent to input.percentDecoded
(percent).For example:
text = QByteArray.fromPercentEncoding("Qt%20is%20great%33") qDebug("%s", text.data()) # reports "Qt is great!"
See also
- static fromRawData(data, size)#
- Parameters:
data – str
size – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Constructs a
QByteArray
that uses the firstsize
bytes of thedata
array. The bytes are not copied. TheQByteArray
will contain thedata
pointer. The caller guarantees thatdata
will not be deleted or modified as long as thisQByteArray
and any copies of it exist that have not been modified. In other words, becauseQByteArray
is an implicitly shared class and the instance returned by this function contains thedata
pointer, the caller must not deletedata
or modify it directly as long as the returnedQByteArray
and any copies exist. However,QByteArray
does not take ownership ofdata
, so theQByteArray
destructor will never delete the rawdata
, even when the lastQByteArray
referring todata
is destroyed.A subsequent attempt to modify the contents of the returned
QByteArray
or any copy made from it will cause it to create a deep copy of thedata
array before doing the modification. This ensures that the rawdata
array itself will never be modified byQByteArray
.Here is an example of how to read data using a
QDataStream
on raw data in memory without copying the raw data into aQByteArray
:mydata = { '\x00', '\x00', '\x03', '\x84', '\x78', '\x9c', '\x3b', '\x76', '\xec', '\x18', '\xc3', '\x31', '\x0a', '\xf1', '\xcc', '\x99', ... '\x6d', '\x5b' data = QByteArray.fromRawData(mydata, sizeof(mydata)) in = QDataStream(data, QIODevice.ReadOnly) ...
Warning
A byte array created with fromRawData() is not ‘\0’-terminated, unless the raw data contains a ‘\0’ byte at position
size
. While that does not matter forQDataStream
or functions likeindexOf()
, passing the byte array to a function accepting aconst char *
expected to be ‘\0’-terminated will fail.See also
setRawData()
data()
constData()
- static fromStdString(s)#
- Parameters:
s – str
- Return type:
Returns a copy of the
str
string as aQByteArray
.See also
toStdString()
fromStdString()
- front()#
- Return type:
int
Returns the first byte in the byte array. Same as
at(0)
.This function is provided for STL compatibility.
Warning
Calling this function on an empty byte array constitutes undefined behavior.
- indexOf(bv[, from=0])#
- Parameters:
bv –
QByteArrayView
from – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the index position of the start of the first occurrence of the sequence of bytes viewed by
bv
in this byte array, searching forward from index positionfrom
. Returns -1 if no match is found.Example:
x = QByteArray("sticky question") y = QByteArrayView("sti") x.indexOf(y) # returns 0 x.indexOf(y, 1) # returns 10 x.indexOf(y, 10) # returns 10 x.indexOf(y, 11) # returns -1
See also
- indexOf(c[, from=0])
- Parameters:
c – int
from – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Returns the index position of the start of the first occurrence of the byte
ch
in this byte array, searching forward from index positionfrom
. Returns -1 if no match is found.Example:
ba = QByteArray("ABCBA") ba.indexOf("B") # returns 1 ba.indexOf("B", 1) # returns 1 ba.indexOf("B", 2) # returns 3 ba.indexOf("X") # returns -1
See also
- insert(i, s, len)#
- Parameters:
i – int
s – str
len – int
- Return type:
This is an overloaded function.
Inserts
len
bytes, starting atdata
, at positioni
in the byte array.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.- insert(i, count, c)
- Parameters:
i – int
count – int
c – int
- Return type:
This is an overloaded function.
Inserts
count
copies of bytech
at index positioni
in the byte array.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.- insert(i, s)
- Parameters:
i – int
s – str
- Return type:
Inserts
s
at index positioni
and returns a reference to this byte array.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.The function is equivalent to
insert(i, QByteArrayView(s))
- insert(i, data)
- Parameters:
i – int
data –
QByteArray
- Return type:
Inserts
data
at index positioni
and returns a reference to this byte array.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.- insert(i, c)
- Parameters:
i – int
c – int
- Return type:
This is an overloaded function.
Inserts byte
ch
at index positioni
in the byte array.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.- insert(i, data)
- Parameters:
i – int
data –
QByteArrayView
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Inserts
data
at index positioni
and returns a reference to this byte array.Example:
ba = QByteArray("Meal") ba.insert(1, QByteArrayView("ontr")) # ba == "Montreal"
For large byte arrays, this operation can be slow ( linear time ), because it requires moving all the bytes at indexes
i
and above by at least one position further in memory.This array grows to accommodate the insertion. If
i
is beyond the end of the array, the array is first extended with space characters to reach thisi
.- isEmpty()#
- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns
true
if the byte array has size 0; otherwise returnsfalse
.Example:
QByteArray().isEmpty() # returns true QByteArray("").isEmpty() # returns true QByteArray("abc").isEmpty() # returns false
See also
- isLower()#
- Return type:
bool
Returns
true
if this byte array is lowercase, that is, if it’s identical to itstoLower()
folding.Note that this does not mean that the byte array only contains lowercase letters; only that it contains no ASCII uppercase letters.
- isNull()#
- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns
true
if this byte array is null; otherwise returnsfalse
.Example:
QByteArray().isNull() # returns true QByteArray("").isNull() # returns false QByteArray("abc").isNull() # returns false
Qt makes a distinction between null byte arrays and empty byte arrays for historical reasons. For most applications, what matters is whether or not a byte array contains any data, and this can be determined using
isEmpty()
.See also
- Parameters:
other –
QByteArray
- Return type:
bool
- isUpper()#
- Return type:
bool
Returns
true
if this byte array is uppercase, that is, if it’s identical to itstoUpper()
folding.Note that this does not mean that the byte array only contains uppercase letters; only that it contains no ASCII lowercase letters.
- isValidUtf8()#
- Return type:
bool
Returns
true
if this byte array contains valid UTF-8 encoded data, orfalse
otherwise.- last(n)#
- Parameters:
n – int
- Return type:
- lastIndexOf(bv, from)#
- Parameters:
bv –
QByteArrayView
from – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the index position of the start of the last occurrence of the sequence of bytes viewed by
bv
in this byte array, searching backward from index positionfrom
.If
from
is -1, the search starts at the last character; if it is -2, at the next to last character and so on.Returns -1 if no match is found.
Example:
x = QByteArray("crazy azimuths") y = QByteArrayView("az") x.lastIndexOf(y) # returns 6 x.lastIndexOf(y, 6) # returns 6 x.lastIndexOf(y, 5) # returns 2 x.lastIndexOf(y, 1) # returns -1
Note
When searching for a 0-length
bv
, the match at the end of the data is excluded from the search by a negativefrom
, even though-1
is normally thought of as searching from the end of the byte array: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value forfrom
or omit thefrom
parameter entirely.See also
- lastIndexOf(c[, from=-1])
- Parameters:
c – int
from – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Returns the index position of the start of the last occurrence of byte
ch
in this byte array, searching backward from index positionfrom
. Iffrom
is -1 (the default), the search starts at the last byte (at indexsize()
- 1). Returns -1 if no match is found.Example:
ba = QByteArray("ABCBA") ba.lastIndexOf("B") # returns 3 ba.lastIndexOf("B", 3) # returns 3 ba.lastIndexOf("B", 2) # returns 1 ba.lastIndexOf("X") # returns -1
See also
- lastIndexOf(bv)
- Parameters:
bv –
QByteArrayView
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Returns the index position of the start of the last occurrence of the sequence of bytes viewed by
bv
in this byte array, searching backward from the end of the byte array. Returns -1 if no match is found.Example:
x = QByteArray("crazy azimuths") y = QByteArrayView("az") x.lastIndexOf(y) # returns 6 x.lastIndexOf(y, 6) # returns 6 x.lastIndexOf(y, 5) # returns 2 x.lastIndexOf(y, 1) # returns -1
See also
- left(n)#
- Parameters:
n – int
- Return type:
- leftJustified(width[, fill=' '[, truncate=false]])#
- Parameters:
width – int
fill – int
truncate – bool
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a byte array of size
width
that contains this byte array padded with thefill
byte.If
truncate
is false and thesize()
of the byte array is more thanwidth
, then the returned byte array is a copy of this byte array.If
truncate
is true and thesize()
of the byte array is more thanwidth
, then any bytes in a copy of the byte array after positionwidth
are removed, and the copy is returned.Example:
x = QByteArray("apple") y = x.leftJustified(8, '.') # y == "apple..."
See also
- length()#
- Return type:
int
Same as
size()
.- mid(index[, len=-1])#
- Parameters:
index – int
len – int
- Return type:
- static number(arg__1[, base=10])#
- Parameters:
arg__1 – int
base – int
- Return type:
This is an overloaded function.
See also
- static number(arg__1[, base=10])
- Parameters:
arg__1 – int
base – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a byte-array representing the whole number
n
as text.Returns a byte array containing a string representing
n
, using the specifiedbase
(ten by default). Bases 2 through 36 are supported, using letters for digits beyond 9: A is ten, B is eleven and so on.Example:
n = 63 QByteArray.number(n) # returns "63" QByteArray.number(n, 16) # returns "3f" QByteArray.number(n, 16).toUpper() # returns "3F"
Note
The format of the number is not localized; the default C locale is used regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- static number(arg__1[, format='g'[, precision=6]])
- Parameters:
arg__1 – float
format – int
precision – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Returns a byte-array representing the floating-point number
n
as text.Returns a byte array containing a string representing
n
, with a givenformat
andprecision
, with the same meanings as fornumber(double, char, int)
. For example:ba = QByteArray.number(12.3456, 'E', 3) # ba == 1.235E+01
See also
- __ne__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __ne__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is not equal to byte arraya2
; otherwise returnsfalse
.See also
- __ne__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is not equal to the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __add__(rhs)#
- Parameters:
rhs – str
- Return type:
This is an overloaded function.
Returns a byte array that is the result of concatenating byte array
a1
and ‘\0’-terminated stringa2
.- __add__(s)
- Parameters:
s – str
- Return type:
str
- __add__(s)
- Parameters:
s – str
- Return type:
str
- __add__(rhs)
- Parameters:
rhs –
QByteArray
- Return type:
Returns a byte array that is the result of concatenating byte array
a1
and byte arraya2
.See also
operator+=()
- __add__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
Returns a byte array that is the result of concatenating byte array
a1
and byte arraya2
.See also
operator+=()
- __add__(a2)
- Parameters:
a2 – int
- Return type:
This is an overloaded function.
Returns a byte array that is the result of concatenating byte array
a1
and bytea2
.- __add__(rhs)
- Parameters:
rhs – int
- Return type:
This is an overloaded function.
Returns a byte array that is the result of concatenating byte array
a1
and bytea2
.- __add__(arg__1)
- Parameters:
arg__1 –
PyByteArray
- Return type:
- __add__(arg__1)
- Parameters:
arg__1 –
PyBytes
- __add__(arg__1)
- Parameters:
arg__1 –
PyByteArray
- Return type:
- __iadd__(arg__1)#
- Parameters:
arg__1 –
PyByteArray
- Return type:
- __iadd__(a)
- Parameters:
a –
QByteArrayView
- Return type:
- __iadd__(c)
- Parameters:
c – int
- Return type:
This is an overloaded function.
Appends the byte
ch
onto the end of this byte array and returns a reference to this byte array.- __iadd__(a)
- Parameters:
a –
QByteArray
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Appends the byte array
ba
onto the end of this byte array and returns a reference to this byte array.Example:
x = QByteArray("free") y = QByteArray("dom") x += y # x == "freedom"
Note:
QByteArray
is an implicitly shared class. Consequently, if you append to an empty byte array, then the byte array will just share the data held inba
. In this case, no copying of data is done, taking constant time . If a shared instance is modified, it will be copied (copy-on-write), taking linear time .If the byte array being appended to is not empty, a deep copy of the data is performed, taking linear time .
This operation typically does not suffer from allocation overhead, because
QByteArray
preallocates extra space at the end of the data so that it may grow without reallocating for each append operation.- __lt__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __lt__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is lexically less than byte arraya2
; otherwise returnsfalse
.See also
- __lt__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is lexically less than the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __lt__(a2)
- Parameters:
a2 – str
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is lexically less than the ‘\0’-terminated stringa2
; otherwise returnsfalse
.See also
- __le__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __le__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is lexically less than or equal to the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __le__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is lexically less than or equal to byte arraya2
; otherwise returnsfalse
.See also
- __eq__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __eq__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is equal to byte arraya2
; otherwise returnsfalse
.See also
- __eq__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is equal to the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __gt__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __gt__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is lexically greater than byte arraya2
; otherwise returnsfalse
.See also
- __gt__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is lexically greater than the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __ge__(arg__1)#
- Parameters:
arg__1 –
PyUnicode
- __ge__(s2)
- Parameters:
s2 – str
- Return type:
bool
Returns
true
if this byte array is greater than or equal to the UTF-8 encoding ofstr
; otherwise returnsfalse
.The comparison is case sensitive.
You can disable this operator by defining
QT_NO_CAST_FROM_ASCII
when you compile your applications. You then need to callfromUtf8()
,fromLatin1()
, orfromLocal8Bit()
explicitly if you want to convert the byte array to aQString
before doing the comparison.- __ge__(a2)
- Parameters:
a2 –
QByteArray
- Return type:
bool
This is an overloaded function.
Returns
true
if byte arraya1
is lexically greater than or equal to byte arraya2
; otherwise returnsfalse
.See also
- operator(i)#
- Parameters:
i – int
- Return type:
int
This is an overloaded function.
Same as at(
i
).- percentDecoded([percent='%'])#
- Parameters:
percent – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Decodes URI/URL-style percent-encoding.
Returns a byte array containing the decoded text. The
percent
parameter allows use of a different character than ‘%’ (for instance, ‘_’ or ‘=’) as the escape character.For example:
encoded = QByteArray("Qt%20is%20great%33") decoded = encoded.percentDecoded() # Set to "Qt is great!"
Note
Given invalid input (such as a string containing the sequence “%G5”, which is not a valid hexadecimal number) the output will be invalid as well. As an example: the sequence “%G5” could be decoded to ‘W’.
See also
- prepend(a)#
- Parameters:
a –
QByteArrayView
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Prepends the byte array view
ba
to this byte array and returns a reference to this byte array.This operation is typically very fast ( constant time ), because
QByteArray
preallocates extra space at the beginning of the data, so it can grow without reallocating the entire array each time.Example:
x = QByteArray("ship") y = QByteArray("air") x.prepend(y) # x == "airship"
This is the same as insert(0,
ba
).- prepend(c)
- Parameters:
c – int
- Return type:
This is an overloaded function.
Prepends the byte
ch
to this byte array.- prepend(a)
- Parameters:
a –
QByteArray
- Return type:
This is an overloaded function.
Prepends
ba
to this byte array.- prepend(s, len)
- Parameters:
s – str
len – int
- Return type:
This is an overloaded function.
Prepends
len
bytes starting atstr
to this byte array. The bytes prepended may include ‘\0’ bytes.- prepend(count, c)
- Parameters:
count – int
c – int
- Return type:
This is an overloaded function.
Prepends
count
copies of bytech
to this byte array.- push_back(a)#
- Parameters:
a –
QByteArrayView
This is an overloaded function.
Same as append(
str
).- push_front(a)#
- Parameters:
a –
QByteArrayView
This is an overloaded function.
Same as prepend(
str
).- remove(index, len)#
- Parameters:
index – int
len – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Removes
len
bytes from the array, starting at index positionpos
, and returns a reference to the array.If
pos
is out of range, nothing happens. Ifpos
is valid, butpos
+len
is larger than the size of the array, the array is truncated at positionpos
.Example:
ba = QByteArray("Montreal") ba.remove(1, 4) # ba == "Meal"
Element removal will preserve the array’s capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call
squeeze()
after the last change to the array’s size.- removeAt(pos)#
- Parameters:
pos – int
- Return type:
Removes the character at index
pos
. Ifpos
is out of bounds (i.e.pos
>=size()
) this function does nothing.See also
- removeFirst()#
- Return type:
Removes the first character in this byte array. If the byte array is empty, this function does nothing.
See also
- removeLast()#
- Return type:
Removes the last character in this byte array. If the byte array is empty, this function does nothing.
See also
- repeated(times)#
- Parameters:
times – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of this byte array repeated the specified number of
times
.If
times
is less than 1, an empty byte array is returned.Example:
ba = QByteArray("ab") ba.repeated(4) # returns "abababab"
- replace(index, len, s, alen)#
- Parameters:
index – int
len – int
s – str
alen – int
- Return type:
This is an overloaded function.
Replaces
len
bytes from index positionpos
withalen
bytes starting at positionafter
. The bytes inserted may include ‘\0’ bytes.- replace(index, len, s)
- Parameters:
index – int
len – int
s –
QByteArrayView
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Replaces
len
bytes from index positionpos
with the byte arrayafter
, and returns a reference to this byte array.Example:
- replace(before, after)
- Parameters:
before – int
after – int
- Return type:
This is an overloaded function.
Replaces every occurrence of the byte
before
with the byteafter
.- replace(before, after)
- Parameters:
before – int
after –
QByteArrayView
- Return type:
This is an overloaded function.
Replaces every occurrence of the byte
before
with the byte arrayafter
.- replace(before, bsize, after, asize)
- Parameters:
before – str
bsize – int
after – str
asize – int
- Return type:
This is an overloaded function.
Replaces every occurrence of the
bsize
bytes starting atbefore
with theasize
bytes starting atafter
. Since the sizes of the strings are given bybsize
andasize
, they may contain ‘\0’ bytes and do not need to be ‘\0’-terminated.- replace(before, after)
- Parameters:
before –
QByteArrayView
after –
QByteArrayView
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Replaces every occurrence of the byte array
before
with the byte arrayafter
.Example:
ba = QByteArray("colour behaviour flavour neighbour") ba.replace(QByteArray("ou"), QByteArray("o")) # ba == "color behavior flavor neighbor"
- reserve(size)#
- Parameters:
size – int
Attempts to allocate memory for at least
size
bytes.If you know in advance how large the byte array will be, you can call this function, and if you call
resize()
often you are likely to get better performance.If in doubt about how much space shall be needed, it is usually better to use an upper bound as
size
, or a high estimate of the most likely size, if a strict upper bound would be much bigger than this. Ifsize
is an underestimate, the array will grow as needed once the reserved size is exceeded, which may lead to a larger allocation than your best overestimate would have and will slow the operation that triggers it.Warning
reserve() reserves memory but does not change the size of the byte array. Accessing data beyond the end of the byte array is undefined behavior. If you need to access memory beyond the current end of the array, use
resize()
.The sole purpose of this function is to provide a means of fine tuning
QByteArray
‘s memory usage. In general, you will rarely ever need to call this function.See also
- resize(size)#
- Parameters:
size – int
Sets the size of the byte array to
size
bytes.If
size
is greater than the current size, the byte array is extended to make itsize
bytes with the extra bytes added to the end. The new bytes are uninitialized.If
size
is less than the current size, bytes beyond positionsize
are excluded from the byte array.Note
While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use
squeeze()
.See also
- resize(size, c)
- Parameters:
size – int
c – int
Sets the size of the byte array to
newSize
bytes.If
newSize
is greater than the current size, the byte array is extended to make itnewSize
bytes with the extra bytes added to the end. The new bytes are initialized toc
.If
newSize
is less than the current size, bytes beyond positionnewSize
are excluded from the byte array.Note
While
resize()
will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, usesqueeze()
.See also
- right(n)#
- Parameters:
n – int
- Return type:
- rightJustified(width[, fill=' '[, truncate=false]])#
- Parameters:
width – int
fill – int
truncate – bool
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a byte array of size
width
that contains thefill
byte followed by this byte array.If
truncate
is false and the size of the byte array is more thanwidth
, then the returned byte array is a copy of this byte array.If
truncate
is true and the size of the byte array is more thanwidth
, then the resulting byte array is truncated at positionwidth
.Example:
x = QByteArray("apple") y = x.rightJustified(8, '.') # y == "...apple"
See also
- setNum(arg__1[, format='g'[, precision=6]])#
- Parameters:
arg__1 – float
format – int
precision – int
- Return type:
This is an overloaded function.
Represent the floating-point number
n
as text.Sets this byte array to a string representing
n
, with a givenformat
andprecision
(with the same meanings as fornumber(double, char, int)
), and returns a reference to this byte array.See also
- setNum(arg__1[, base=10])
- Parameters:
arg__1 – int
base – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Represent the whole number
n
as text.Sets this byte array to a string representing
n
in basebase
(ten by default) and returns a reference to this byte array. Bases 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.Example:
ba = QByteArray() n = 63 ba.setNum(n) # ba == "63" ba.setNum(n, 16) # ba == "3f"
Note
The format of the number is not localized; the default C locale is used regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- setNum(arg__1[, base=10])
- Parameters:
arg__1 – int
base – int
- Return type:
This is an overloaded function.
See also
- setRawData(a, n)#
- Parameters:
a – str
n – int
- Return type:
Resets the
QByteArray
to use the firstsize
bytes of thedata
array. The bytes are not copied. TheQByteArray
will contain thedata
pointer. The caller guarantees thatdata
will not be deleted or modified as long as thisQByteArray
and any copies of it exist that have not been modified.This function can be used instead of
fromRawData()
to re-use existingQByteArray
objects to save memory re-allocations.See also
fromRawData()
data()
constData()
- shrink_to_fit()#
This function is provided for STL compatibility. It is equivalent to
squeeze()
.- simplified()#
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of this byte array that has spacing characters removed from the start and end, and in which each sequence of internal spacing characters is replaced with a single space.
The spacing characters are those for which the standard C++
isspace()
function returnstrue
in the C locale; these are the ASCII characters tabulation ‘\t’, line feed ‘\n’, carriage return ‘\r’, vertical tabulation ‘\v’, form feed ‘\f’, and space ‘ ‘.Example:
ba = QByteArray(" lots\t of\nwhitespace\r\n ") ba = ba.simplified() # ba == "lots of whitespace"
See also
trimmed()
SpecialCharacter
Spacing Characters
- size()#
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the number of bytes in this byte array.
The last byte in the byte array is at position size() - 1. In addition,
QByteArray
ensures that the byte at position size() is always ‘\0’, so that you can use the return value ofdata()
andconstData()
as arguments to functions that expect ‘\0’-terminated strings. If theQByteArray
object was created from araw data
that didn’t include the trailing ‘\0’-termination byte, thenQByteArray
doesn’t add it automatically unless a deep copy is created.Example:
- sliced(pos)#
- Parameters:
pos – int
- Return type:
- sliced(pos, n)
- Parameters:
pos – int
n – int
- Return type:
- split(sep)#
- Parameters:
sep – int
- Return type:
.list of QByteArray
Splits the byte array into subarrays wherever
sep
occurs, and returns the list of those arrays. Ifsep
does not match anywhere in the byte array, split() returns a single-element list containing this byte array.- squeeze()#
Releases any memory not required to store the array’s data.
The sole purpose of this function is to provide a means of fine tuning
QByteArray
‘s memory usage. In general, you will rarely ever need to call this function.See also
- startsWith(c)#
- Parameters:
c – int
- Return type:
bool
This is an overloaded function.
Returns
true
if this byte array starts with bytech
; otherwise returnsfalse
.- startsWith(bv)
- Parameters:
bv –
QByteArrayView
- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns
true
if this byte array starts with the sequence of bytes viewed bybv
; otherwise returnsfalse
.Example:
url = QByteArray("ftp://ftp.qt-project.org/") if url.startsWith("ftp:"): ...
See also
- swap(other)#
- Parameters:
other –
QByteArray
Swaps byte array
other
with this byte array. This operation is very fast and never fails.- toBase64([options=QByteArray.Base64Option.Base64Encoding])#
- Parameters:
options – Combination of
Base64Option
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of the byte array, encoded using the options
options
.text = QByteArray("Qt is great!") text.toBase64() # returns "UXQgaXMgZ3JlYXQh" text = QByteArray("") text.toBase64(QByteArray.Base64Encoding | QByteArray.OmitTrailingEquals) # returns "PHA+SGVsbG8/PC9wPg" text.toBase64(QByteArray.Base64Encoding) # returns "PHA+SGVsbG8/PC9wPg==" text.toBase64(QByteArray.Base64UrlEncoding) # returns "PHA-SGVsbG8_PC9wPg==" text.toBase64(QByteArray.Base64UrlEncoding | QByteArray.OmitTrailingEquals) # returns "PHA-SGVsbG8_PC9wPg"
The algorithm used to encode Base64-encoded data is defined in RFC 4648.
See also
- toDouble()#
- Return type:
float
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the byte array converted to a
double
value.Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.string = QByteArray("1234.56") ok = bool() a = string.toDouble(ok) # a == 1234.56, ok == true string = "1234.56 Volt" a = str.toDouble(ok) # a == 0, ok == false
Warning
The
QByteArray
content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.This function ignores leading and trailing whitespace.
See also
- toFloat()#
- Return type:
float
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the byte array converted to a
float
value.Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.string = QByteArray("1234.56") ok = bool() a = string.toFloat(ok) # a == 1234.56, ok == true string = "1234.56 Volt" a = str.toFloat(ok) # a == 0, ok == false
Warning
The
QByteArray
content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.This function ignores leading and trailing whitespace.
See also
- toHex([separator='\0'])#
- Parameters:
separator – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a hex encoded copy of the byte array.
The hex encoding uses the numbers 0-9 and the letters a-f.
If
separator
is not ‘\0’, the separator character is inserted between the hex bytes.Example:
macAddress = QByteArray.fromHex("123456abcdef") macAddress.toHex(':') # returns "12:34:56:ab:cd:ef" macAddress.toHex(0) # returns "123456abcdef"
See also
- toInt([base=10])#
- Parameters:
base – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the byte array converted to an
int
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.str = QByteArray("FF") ok = bool() hex = str.toInt(ok, 16) # hex == 255, ok == true dec = str.toInt(ok, 10) # dec == 0, ok == false
Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toLong([base=10])#
- Parameters:
base – int
- Return type:
int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the byte array converted to a
long
int using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.str = QByteArray("FF") ok = bool() hex = str.toLong(ok, 16) # hex == 255, ok == true dec = str.toLong(ok, 10) # dec == 0, ok == false
Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toLongLong([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to a
long long
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toLower()#
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of the byte array in which each ASCII uppercase letter converted to lowercase.
Example:
- toPercentEncoding([exclude=QByteArray()[, include=QByteArray()[, percent='%']]])#
- Parameters:
exclude –
QByteArray
include –
QByteArray
percent – int
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a URI/URL-style percent-encoded copy of this byte array. The
percent
parameter allows you to override the default ‘%’ character for another.By default, this function will encode all bytes that are not one of the following:
ALPHA (“a” to “z” and “A” to “Z”) / DIGIT (0 to 9) / “-” / “.” / “_” / “~”
To prevent bytes from being encoded pass them to
exclude
. To force bytes to be encoded pass them toinclude
. Thepercent
character is always encoded.Example:
QByteArray text = "{a fishy string?}" QByteArray ba = text.toPercentEncoding("{}", "s") qDebug("%s", ba.constData()) # prints "{a fi%73hy %73tring%3F}"
The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
See also
- toShort([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to a
short
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toStdString()#
- Return type:
str
Returns a std::string object with the data contained in this
QByteArray
.This operator is mostly useful to pass a
QByteArray
to a function that accepts a std::string object.See also
fromStdString()
toStdString()
- toUInt([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to an
unsigned int
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toULong([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to an
unsigned long int
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toULongLong([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to an
unsigned long long
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toUShort([base=10])#
- Parameters:
base – int
- Return type:
int
Returns the byte array converted to an
unsigned short
using basebase
, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.If
base
is 0, the base is determined automatically using the following rules: If the byte array begins with “0x”, it is assumed to be hexadecimal (base 16); otherwise, if it begins with “0b”, it is assumed to be binary (base 2); otherwise, if it begins with “0”, it is assumed to be octal (base 8); otherwise it is assumed to be decimal.Returns 0 if the conversion fails.
If
ok
is notNone
, failure is reported by setting *``ok`` tofalse
, and success by setting *``ok`` totrue
.Note
The conversion of the number is performed in the default C locale, regardless of the user’s locale. Use
QLocale
to perform locale-aware conversions between numbers and strings.- toUpper()#
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of the byte array in which each ASCII lowercase letter converted to uppercase.
Example:
- trimmed()#
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a copy of this byte array with spacing characters removed from the start and end.
The spacing characters are those for which the standard C++
isspace()
function returnstrue
in the C locale; these are the ASCII characters tabulation ‘\t’, line feed ‘\n’, carriage return ‘\r’, vertical tabulation ‘\v’, form feed ‘\f’, and space ‘ ‘.Example:
ba = QByteArray(" lots\t of\nwhitespace\r\n ") ba = ba.trimmed() # ba == "lots\t of\nwhitespace"
Unlike
simplified()
, trimmed() leaves internal spacing unchanged.See also
simplified()
SpecialCharacter
Spacing Characters
- truncate(pos)#
- Parameters:
pos – int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Truncates the byte array at index position
pos
.If
pos
is beyond the end of the array, nothing happens.Example: