QIODevice¶
Inherited by: QBuffer, QFile, QFileDevice, QProcess, QSaveFile, QTemporaryFile, QAbstractSocket, QLocalSocket, QNetworkReply, QSslSocket, QTcpSocket, QUdpSocket
Synopsis¶
Functions¶
def
commitTransaction
()def
currentReadChannel
()def
currentWriteChannel
()def
errorString
()def
getChar
()def
isOpen
()def
isReadable
()def
isTextModeEnabled
()def
isTransactionStarted
()def
isWritable
()def
openMode
()def
peek
(maxlen)def
putChar
(c)def
read
(maxlen)def
readAll
()def
readChannelCount
()def
readLine
([maxlen=0])def
rollbackTransaction
()def
setCurrentReadChannel
(channel)def
setCurrentWriteChannel
(channel)def
setErrorString
(errorString)def
setOpenMode
(openMode)def
setTextModeEnabled
(enabled)def
skip
(maxSize)def
startTransaction
()def
ungetChar
(c)def
write
(data)def
writeChannelCount
()
Virtual functions¶
def
atEnd
()def
bytesAvailable
()def
bytesToWrite
()def
canReadLine
()def
close
()def
isSequential
()def
open
(mode)def
pos
()def
readData
(, maxlen)def
readLineData
(, maxlen)def
reset
()def
seek
(pos)def
size
()def
waitForBytesWritten
(msecs)def
waitForReadyRead
(msecs)def
writeData
(data, len)
Signals¶
def
aboutToClose
()def
bytesWritten
(bytes)def
channelBytesWritten
(channel, bytes)def
channelReadyRead
(channel)def
readChannelFinished
()def
readyRead
()
Detailed Description¶
QIODevice
provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data, such asQFile
,QBuffer
andQTcpSocket
.QIODevice
is abstract and cannot be instantiated, but it is common to use the interface it defines to provide device-independent I/O features. For example, Qt’s XML classes operate on aQIODevice
pointer, allowing them to be used with various devices (such as files and buffers).Before accessing the device,
open()
must be called to set the correctOpenMode
(such asReadOnly
orReadWrite
). You can then write to the device withwrite()
orputChar()
, and read by calling eitherread()
,readLine()
, orreadAll()
. Callclose()
when you are done with the device.
QIODevice
distinguishes between two types of devices: random-access devices and sequential devices.
Random-access devices support seeking to arbitrary positions using
seek()
. The current position in the file is available by callingpos()
.QFile
andQBuffer
are examples of random-access devices.Sequential devices don’t support seeking to arbitrary positions. The data must be read in one pass. The functions
pos()
andsize()
don’t work for sequential devices.QTcpSocket
andQProcess
are examples of sequential devices.You can use
isSequential()
to determine the type of device.
QIODevice
emitsreadyRead()
when new data is available for reading; for example, if new data has arrived on the network or if additional data is appended to a file that you are reading from. You can callbytesAvailable()
to determine the number of bytes that are currently available for reading. It’s common to usebytesAvailable()
together with thereadyRead()
signal when programming with asynchronous devices such asQTcpSocket
, where fragments of data can arrive at arbitrary points in time.QIODevice
emits thebytesWritten()
signal every time a payload of data has been written to the device. UsebytesToWrite()
to determine the current amount of data waiting to be written.Certain subclasses of
QIODevice
, such asQTcpSocket
andQProcess
, are asynchronous. This means that I/O functions such aswrite()
orread()
always return immediately, while communication with the device itself may happen when control goes back to the event loop.QIODevice
provides functions that allow you to force these operations to be performed immediately, while blocking the calling thread and without entering the event loop. This allowsQIODevice
subclasses to be used without an event loop, or in a separate thread:
waitForReadyRead()
- This function suspends operation in the calling thread until new data is available for reading.
waitForBytesWritten()
- This function suspends operation in the calling thread until one payload of data has been written to the device.waitFor….() - Subclasses of
QIODevice
implement blocking functions for device-specific operations. For example,QProcess
has a function calledwaitForStarted()
which suspends operation in the calling thread until the process has started.Calling these functions from the main, GUI thread, may cause your user interface to freeze. Example:
gzip = QProcess() gzip.start("gzip", ["-c"]) if not gzip.waitForStarted(): return False gzip.write("uncompressed data") compressed = QByteArray() while gzip.waitForReadyRead(): compressed += gzip.readAll()By subclassing
QIODevice
, you can provide the same interface to your own I/O devices. Subclasses ofQIODevice
are only required to implement the protectedreadData()
andwriteData()
functions.QIODevice
uses these functions to implement all its convenience functions, such asgetChar()
,readLine()
andwrite()
.QIODevice
also handles access control for you, so you can safely assume that the device is opened in write mode ifwriteData()
is called.Some subclasses, such as
QFile
andQTcpSocket
, are implemented using a memory buffer for intermediate storing of data. This reduces the number of required device accessing calls, which are often very slow. Buffering makes functions likegetChar()
andputChar()
fast, as they can operate on the memory buffer instead of directly on the device itself. Certain I/O operations, however, don’t work well with a buffer. For example, if several users open the same device and read it character by character, they may end up reading the same data when they meant to read a separate chunk each. For this reason,QIODevice
allows you to bypass any buffering by passing the Unbuffered flag toopen()
. When subclassingQIODevice
, remember to bypass any buffer you may use when the device is open in Unbuffered mode.Usually, the incoming data stream from an asynchronous device is fragmented, and chunks of data can arrive at arbitrary points in time. To handle incomplete reads of data structures, use the transaction mechanism implemented by
QIODevice
. SeestartTransaction()
and related functions for more details.Some sequential devices support communicating via multiple channels. These channels represent separate streams of data that have the property of independently sequenced delivery. Once the device is opened, you can determine the number of channels by calling the
readChannelCount()
andwriteChannelCount()
functions. To switch between channels, callsetCurrentReadChannel()
andsetCurrentWriteChannel()
, respectively.QIODevice
also provides additional signals to handle asynchronous communication on a per-channel basis.
- class PySide2.QtCore.QIODevice¶
PySide2.QtCore.QIODevice(parent)
- param parent:
Constructs a
QIODevice
object.Constructs a
QIODevice
object with the givenparent
.
- PySide2.QtCore.QIODevice.OpenModeFlag¶
This enum is used with
open()
to describe the mode in which a device is opened. It is also returned byopenMode()
.Constant
Description
QIODevice.NotOpen
The device is not open.
QIODevice.ReadOnly
The device is open for reading.
QIODevice.WriteOnly
The device is open for writing. Note that, for file-system subclasses (e.g.
QFile
), this mode implies Truncate unless combined with , Append or .QIODevice.ReadWrite
The device is open for reading and writing.
QIODevice.Append
The device is opened in append mode so that all data is written to the end of the file.
QIODevice.Truncate
If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
QIODevice.Text
When reading, the end-of-line terminators are translated to ‘\n’. When writing, the end-of-line terminators are translated to the local encoding, for example ‘\r\n’ for Win32.
QIODevice.Unbuffered
Any buffer in the device is bypassed.
QIODevice.NewOnly
Fail if the file to be opened already exists. Create and open the file only if it does not exist. There is a guarantee from the operating system that you are the only one creating and opening the file. Note that this mode implies , and combining it with is allowed. This flag currently only affects
QFile
. Other classes might use this flag in the future, but until then using this flag with any classes other thanQFile
may result in undefined behavior. (since Qt 5.11)QIODevice.ExistingOnly
Fail if the file to be opened does not exist. This flag must be specified alongside , , or . Note that using this flag with alone is redundant, as already fails when the file does not exist. This flag currently only affects
QFile
. Other classes might use this flag in the future, but until then using this flag with any classes other thanQFile
may result in undefined behavior. (since Qt 5.11)Certain flags, such as
Unbuffered
andTruncate
, are meaningless when used with some subclasses. Some of these restrictions are implied by the type of device that is represented by a subclass. In other cases, the restriction may be due to the implementation, or may be imposed by the underlying platform; for example,QTcpSocket
does not supportUnbuffered
mode, and limitations in the native API preventQFile
from supportingUnbuffered
on Windows.
- PySide2.QtCore.QIODevice.aboutToClose()¶
- PySide2.QtCore.QIODevice.atEnd()¶
- Return type:
bool
Returns
true
if the current read and write position is at the end of the device (i.e. there is no more data available for reading on the device); otherwise returnsfalse
.For some devices, can return true even though there is more data to read. This special case only applies to devices that generate data in direct response to you calling
read()
(e.g.,/dev
or/proc
files on Unix and macOS, or console input /stdin
on all platforms).See also
- PySide2.QtCore.QIODevice.bytesAvailable()¶
- Return type:
int
Returns the number of bytes that are available for reading. This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading.
Subclasses that reimplement this function must call the base implementation in order to include the size of the buffer of
QIODevice
. Example:def bytesAvailable(self): return buffer.size() + QIODevice.bytesAvailable()
See also
- PySide2.QtCore.QIODevice.bytesToWrite()¶
- Return type:
int
For buffered devices, this function returns the number of bytes waiting to be written. For devices with no buffer, this function returns 0.
Subclasses that reimplement this function must call the base implementation in order to include the size of the buffer of
QIODevice
.See also
- PySide2.QtCore.QIODevice.bytesWritten(bytes)¶
- Parameters:
bytes – int
- PySide2.QtCore.QIODevice.canReadLine()¶
- Return type:
bool
Returns
true
if a complete line of data can be read from the device; otherwise returnsfalse
.Note that unbuffered devices, which have no way of determining what can be read, always return false.
This function is often called in conjunction with the
readyRead()
signal.Subclasses that reimplement this function must call the base implementation in order to include the contents of the
QIODevice
‘s buffer. Example:def canReadLine(self): return buffer.contains('\n') or QIODevice.canReadLine()
See also
- PySide2.QtCore.QIODevice.channelBytesWritten(channel, bytes)¶
- Parameters:
channel – int
bytes – int
- PySide2.QtCore.QIODevice.channelReadyRead(channel)¶
- Parameters:
channel – int
- PySide2.QtCore.QIODevice.close()¶
First emits
aboutToClose()
, then closes the device and sets itsOpenMode
toNotOpen
. The error string is also reset.See also
setOpenMode()
OpenMode
- PySide2.QtCore.QIODevice.commitTransaction()¶
Completes a read transaction.
For sequential devices, all data recorded in the internal buffer during the transaction will be discarded.
See also
- PySide2.QtCore.QIODevice.currentReadChannel()¶
- Return type:
int
Returns the index of the current read channel.
- PySide2.QtCore.QIODevice.currentWriteChannel()¶
- Return type:
int
Returns the index of the current write channel.
- PySide2.QtCore.QIODevice.errorString()¶
- Return type:
str
Returns a human-readable description of the last device error that occurred.
See also
- PySide2.QtCore.QIODevice.getChar()¶
- Return type:
bool
Reads one character from the device and stores it in
c
. Ifc
isNone
, the character is discarded. Returnstrue
on success; otherwise returnsfalse
.See also
- PySide2.QtCore.QIODevice.isOpen()¶
- Return type:
bool
Returns
true
if the device is open; otherwise returnsfalse
. A device is open if it can be read from and/or written to. By default, this function returnsfalse
ifopenMode()
returnsNotOpen
.See also
openMode()
OpenMode
- PySide2.QtCore.QIODevice.isReadable()¶
- Return type:
bool
Returns
true
if data can be read from the device; otherwise returns false. UsebytesAvailable()
to determine how many bytes can be read.This is a convenience function which checks if the
OpenMode
of the device contains theReadOnly
flag.See also
openMode()
OpenMode
- PySide2.QtCore.QIODevice.isSequential()¶
- Return type:
bool
Returns
true
if this device is sequential; otherwise returns false.Sequential devices, as opposed to a random-access devices, have no concept of a start, an end, a size, or a current position, and they do not support seeking. You can only read from the device when it reports that data is available. The most common example of a sequential device is a network socket. On Unix, special files such as /dev/zero and fifo pipes are sequential.
Regular files, on the other hand, do support random access. They have both a size and a current position, and they also support seeking backwards and forwards in the data stream. Regular files are non-sequential.
See also
- PySide2.QtCore.QIODevice.isTextModeEnabled()¶
- Return type:
bool
Returns
true
if theText
flag is enabled; otherwise returnsfalse
.See also
- PySide2.QtCore.QIODevice.isTransactionStarted()¶
- Return type:
bool
Returns
true
if a transaction is in progress on the device, otherwisefalse
.See also
- PySide2.QtCore.QIODevice.isWritable()¶
- Return type:
bool
Returns
true
if data can be written to the device; otherwise returns false.This is a convenience function which checks if the
OpenMode
of the device contains theWriteOnly
flag.See also
openMode()
OpenMode
- PySide2.QtCore.QIODevice.open(mode)¶
- Parameters:
mode –
OpenMode
- Return type:
bool
Opens the device and sets its
OpenMode
tomode
. Returnstrue
if successful; otherwise returnsfalse
. This function should be called from any reimplementations of or other functions that open the device.See also
openMode()
OpenMode
- PySide2.QtCore.QIODevice.openMode()¶
- Return type:
OpenMode
Returns the mode in which the device has been opened; i.e.
ReadOnly
orWriteOnly
.See also
setOpenMode()
OpenMode
- PySide2.QtCore.QIODevice.peek(maxlen)¶
- Parameters:
maxlen – int
- Return type:
This is an overloaded function.
Peeks at most
maxSize
bytes from the device, returning the data peeked as aQByteArray
.Example:
def isExeFile(file_): return file_.peek(2) == "MZ"
This function has no way of reporting errors; returning an empty
QByteArray
can mean either that no data was currently available for peeking, or that an error occurred.See also
- PySide2.QtCore.QIODevice.pos()¶
- Return type:
int
For random-access devices, this function returns the position that data is written to or read from. For sequential devices or closed devices, where there is no concept of a “current position”, 0 is returned.
The current read/write position of the device is maintained internally by
QIODevice
, so reimplementing this function is not necessary. When subclassingQIODevice
, useseek()
to notifyQIODevice
about changes in the device position.See also
- PySide2.QtCore.QIODevice.putChar(c)¶
- Parameters:
c –
char
- Return type:
bool
Writes the character
c
to the device. Returnstrue
on success; otherwise returnsfalse
.See also
- PySide2.QtCore.QIODevice.read(maxlen)¶
- Parameters:
maxlen – int
- Return type:
This is an overloaded function.
Reads at most
maxSize
bytes from the device, and returns the data read as aQByteArray
.This function has no way of reporting errors; returning an empty
QByteArray
can mean either that no data was currently available for reading, or that an error occurred.
- PySide2.QtCore.QIODevice.readAll()¶
- Return type:
Reads all remaining data from the device, and returns it as a byte array.
This function has no way of reporting errors; returning an empty
QByteArray
can mean either that no data was currently available for reading, or that an error occurred.
- PySide2.QtCore.QIODevice.readChannelCount()¶
- Return type:
int
Returns the number of available read channels if the device is open; otherwise returns 0.
See also
- PySide2.QtCore.QIODevice.readChannelFinished()¶
- PySide2.QtCore.QIODevice.readData(maxlen)¶
- Parameters:
maxlen – int
- Return type:
PyObject
Reads up to
maxSize
bytes from the device intodata
, and returns the number of bytes read or -1 if an error occurred.If there are no bytes to be read and there can never be more bytes available (examples include socket closed, pipe closed, sub-process finished), this function returns -1.
This function is called by
QIODevice
. Reimplement this function when creating a subclass ofQIODevice
.When reimplementing this function it is important that this function reads all the required data before returning. This is required in order for
QDataStream
to be able to operate on the class.QDataStream
assumes all the requested information was read and therefore does not retry reading if there was a problem.This function might be called with a maxSize of 0, which can be used to perform post-reading operations.
See also
- PySide2.QtCore.QIODevice.readLine([maxlen=0])¶
- Parameters:
maxlen – int
- Return type:
This is an overloaded function.
Reads a line from the device, but no more than
maxSize
characters, and returns the result as a byte array.This function has no way of reporting errors; returning an empty
QByteArray
can mean either that no data was currently available for reading, or that an error occurred.
- PySide2.QtCore.QIODevice.readLineData(maxlen)¶
- Parameters:
maxlen – int
- Return type:
PyObject
Reads up to
maxSize
characters intodata
and returns the number of characters read.This function is called by
readLine()
, and provides its base implementation, usinggetChar()
. Buffered devices can improve the performance ofreadLine()
by reimplementing this function.readLine()
appends a ‘\0’ byte todata
; does not need to do this.If you reimplement this function, be careful to return the correct value: it should return the number of bytes read in this line, including the terminating newline, or 0 if there is no line to be read at this point. If an error occurs, it should return -1 if and only if no bytes were read. Reading past EOF is considered an error.
- PySide2.QtCore.QIODevice.readyRead()¶
- PySide2.QtCore.QIODevice.reset()¶
- Return type:
bool
Seeks to the start of input for random-access devices. Returns true on success; otherwise returns
false
(for example, if the device is not open).Note that when using a
QTextStream
on aQFile
, calling on theQFile
will not have the expected result becauseQTextStream
buffers the file. Use theseek()
function instead.See also
- PySide2.QtCore.QIODevice.rollbackTransaction()¶
Rolls back a read transaction.
Restores the input stream to the point of the
startTransaction()
call. This function is commonly used to rollback the transaction when an incomplete read was detected prior to committing the transaction.See also
- PySide2.QtCore.QIODevice.seek(pos)¶
- Parameters:
pos – int
- Return type:
bool
For random-access devices, this function sets the current position to
pos
, returning true on success, or false if an error occurred. For sequential devices, the default behavior is to produce a warning and return false.When subclassing
QIODevice
, you must call at the start of your function to ensure integrity withQIODevice
‘s built-in buffer.See also
- PySide2.QtCore.QIODevice.setCurrentReadChannel(channel)¶
- Parameters:
channel – int
Sets the current read channel of the
QIODevice
to the givenchannel
. The current input channel is used by the functionsread()
,readAll()
,readLine()
, andgetChar()
. It also determines which channel triggersQIODevice
to emitreadyRead()
.
- PySide2.QtCore.QIODevice.setCurrentWriteChannel(channel)¶
- Parameters:
channel – int
Sets the current write channel of the
QIODevice
to the givenchannel
. The current output channel is used by the functionswrite()
,putChar()
. It also determines which channel triggersQIODevice
to emitbytesWritten()
.See also
- PySide2.QtCore.QIODevice.setErrorString(errorString)¶
- Parameters:
errorString – str
Sets the human readable description of the last device error that occurred to
str
.See also
- PySide2.QtCore.QIODevice.setOpenMode(openMode)¶
- Parameters:
openMode –
OpenMode
Sets the
OpenMode
of the device toopenMode
. Call this function to set the open mode if the flags change after the device has been opened.See also
openMode()
OpenMode
- PySide2.QtCore.QIODevice.setTextModeEnabled(enabled)¶
- Parameters:
enabled – bool
If
enabled
is true, this function sets theText
flag on the device; otherwise theText
flag is removed. This feature is useful for classes that provide custom end-of-line handling on aQIODevice
.The IO device should be opened before calling this function.
See also
- PySide2.QtCore.QIODevice.size()¶
- Return type:
int
For open random-access devices, this function returns the size of the device. For open sequential devices,
bytesAvailable()
is returned.If the device is closed, the size returned will not reflect the actual size of the device.
See also
- PySide2.QtCore.QIODevice.skip(maxSize)¶
- Parameters:
maxSize – int
- Return type:
int
Skips up to
maxSize
bytes from the device. Returns the number of bytes actually skipped, or -1 on error.This function does not wait and only discards the data that is already available for reading.
If the device is opened in text mode, end-of-line terminators are translated to ‘\n’ symbols and count as a single byte identically to the
read()
andpeek()
behavior.This function works for all devices, including sequential ones that cannot
seek()
. It is optimized to skip unwanted data after apeek()
call.For random-access devices, can be used to seek forward from the current position. Negative
maxSize
values are not allowed.
- PySide2.QtCore.QIODevice.startTransaction()¶
Starts a new read transaction on the device.
Defines a restorable point within the sequence of read operations. For sequential devices, read data will be duplicated internally to allow recovery in case of incomplete reads. For random-access devices, this function saves the current position. Call
commitTransaction()
orrollbackTransaction()
to finish the transaction.Note
Nesting transactions is not supported.
See also
- PySide2.QtCore.QIODevice.ungetChar(c)¶
- Parameters:
c –
char
Puts the character
c
back into the device, and decrements the current position unless the position is 0. This function is usually called to “undo” agetChar()
operation, such as when writing a backtracking parser.If
c
was not previously read from the device, the behavior is undefined.Note
This function is not available while a transaction is in progress.
- PySide2.QtCore.QIODevice.waitForBytesWritten(msecs)¶
- Parameters:
msecs – int
- Return type:
bool
For buffered devices, this function waits until a payload of buffered written data has been written to the device and the
bytesWritten()
signal has been emitted, or untilmsecs
milliseconds have passed. If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately.Returns
true
if a payload of data was written to the device; otherwise returnsfalse
(i.e. if the operation timed out, or if an error occurred).This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.
If called from within a slot connected to the
bytesWritten()
signal,bytesWritten()
will not be reemitted.Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns
false
.Warning
Calling this function from the main (GUI) thread might cause your user interface to freeze.
See also
- PySide2.QtCore.QIODevice.waitForReadyRead(msecs)¶
- Parameters:
msecs – int
- Return type:
bool
Blocks until new data is available for reading and the
readyRead()
signal has been emitted, or untilmsecs
milliseconds have passed. If msecs is -1, this function will not time out.Returns
true
if new data is available for reading; otherwise returns false (if the operation timed out or if an error occurred).This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.
If called from within a slot connected to the
readyRead()
signal,readyRead()
will not be reemitted.Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns
false
.Warning
Calling this function from the main (GUI) thread might cause your user interface to freeze.
See also
- PySide2.QtCore.QIODevice.write(data)¶
- Parameters:
data –
PySide2.QtCore.QByteArray
- Return type:
int
- PySide2.QtCore.QIODevice.writeChannelCount()¶
- Return type:
int
Returns the number of available write channels if the device is open; otherwise returns 0.
See also
- PySide2.QtCore.QIODevice.writeData(data, len)¶
- Parameters:
data – str
len – int
- Return type:
int
Writes up to
maxSize
bytes fromdata
to the device. Returns the number of bytes written, or -1 if an error occurred.This function is called by
QIODevice
. Reimplement this function when creating a subclass ofQIODevice
.When reimplementing this function it is important that this function writes all the data available before returning. This is required in order for
QDataStream
to be able to operate on the class.QDataStream
assumes all the information was written and therefore does not retry writing if there was a problem.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.