内容表

上一话题

QHistoryState

下一话题

QIdentityProxyModel

QIODevice

QIODevice 类是 Qt 中所有 I/O 设备的基接口类。 更多

Inheritance diagram of PySide2.QtCore.QIODevice

继承者: QBuffer , QFile , QFileDevice , QProcess , QSaveFile , QTemporaryFile , QAbstractSocket , QLocalSocket , QNetworkReply , QSslSocket , QTcpSocket , QUdpSocket

概要

虚函数

信号

详细描述

QIODevice provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data, such as QFile , QBuffer and QTcpSocket . 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 a QIODevice pointer, allowing them to be used with various devices (such as files and buffers).

在访问设备之前, open() must be called to set the correct OpenMode (譬如 ReadOnly or ReadWrite )。然后,可以写入设备采用 write() or putChar() , and read by calling either read() , readLine() ,或 readAll() 。调用 close() when you are done with the device.

QIODevice distinguishes between two types of devices: random-access devices and sequential devices.

  • 随机访问设备支持寻址到任意位置使用 seek() . The current position in the file is available by calling pos() . QFile and QBuffer 是随机访问设备范例。

  • Sequential devices don’t support seeking to arbitrary positions. The data must be read in one pass. The functions pos() and size() don’t work for sequential devices. QTcpSocket and QProcess 是顺序设备范例。

可以使用 isSequential() to determine the type of device.

QIODevice 发射 readyRead() 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 call bytesAvailable() to determine the number of bytes that are currently available for reading. It’s common to use bytesAvailable() together with the readyRead() signal when programming with asynchronous devices such as QTcpSocket , where fragments of data can arrive at arbitrary points in time. QIODevice 发射 bytesWritten() signal every time a payload of data has been written to the device. Use bytesToWrite() to determine the current amount of data waiting to be written.

某些子类化的 QIODevice ,譬如 QTcpSocket and QProcess , 是异步的。这意味着 I/O 函数,譬如 write() or read() 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 allows QIODevice 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 拥有函数称为 waitForStarted() 挂起调用线程中的操作,直到进程启动为止。

从主 GUI 线程调用这些函数可能导致用户界面被冻结。范例:

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 of QIODevice are only required to implement the protected readData() and writeData() 函数。 QIODevice uses these functions to implement all its convenience functions, such as getChar() , readLine() and write() . QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData() 被调用。

某些子类,譬如 QFile and QTcpSocket ,使用内存缓冲实现数据的中间体存储。这减少了要求设备的访问调用 (经常非常慢) 数。缓冲使函数像 getChar() and putChar() 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 to open() . When subclassing QIODevice , 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 。见 startTransaction() and related functions for more details.

某些顺序设备支持凭借多个通道的通信。这些通道表示拥有独立顺序交付特性的单独数据流。设备被打开后,就可以确定通道数通过调用 readChannelCount() and writeChannelCount() functions. To switch between channels, call setCurrentReadChannel() and setCurrentWriteChannel() ,分别。 QIODevice also provides additional signals to handle asynchronous communication on a per-channel basis.

class QIODevice

QIODevice(parent)

param parent

QObject

构造 QIODevice 对象。

构造 QIODevice 对象采用给定 parent .

PySide2.QtCore.QIODevice. OpenModeFlag

此枚举用于 open() to describe the mode in which a device is opened. It is also returned by openMode() .

常量

描述

QIODevice.NotOpen

设备未打开。

QIODevice.ReadOnly

打开设备以供读取。

QIODevice.WriteOnly

打开设备以供写入。注意,对于文件系统子类 (如 QFile ), this mode implies Truncate unless combined with , Append or .

QIODevice.ReadWrite

设备打开为读取和写入。

QIODevice.Append

以追加方式打开设备,以便将所有数据写入文件末尾。

QIODevice.Truncate

若可能,会截取设备在它被打开之前。设备的所有早期内容将丢失。

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

绕过任何设备缓冲。

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 than QFile 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 than QFile may result in undefined behavior. (since Qt 5.11)

某些标志,如 Unbuffered and Truncate 没有意义,当用于某些子类时。其中某些限定由子类表示的设备类型所隐含。在其它情况下,限定可能是由于实现,或可能是通过底层平台强加;例如, QTcpSocket 不支持 Unbuffered 模式,且局限在本机 API 以阻止 QFile 从支持 Unbuffered 在 Windows。

PySide2.QtCore.QIODevice. aboutToClose ( )
PySide2.QtCore.QIODevice. atEnd ( )
返回类型

bool

返回 true 若当前读写位置在设备的末端 (即:设备中没有更多可供读取的数据);否则返回 false .

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() (如, /dev or /proc 文件在 Unix 和 macOS,或控制台输入 / stdin 在所有平台)。

PySide2.QtCore.QIODevice. bytesAvailable ( )
返回类型

qint64

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 。范例:

def bytesAvailable(self):
    return buffer.size() + QIODevice.bytesAvailable()
											
PySide2.QtCore.QIODevice. bytesToWrite ( )
返回类型

qint64

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 .

PySide2.QtCore.QIODevice. bytesWritten ( bytes )
参数

bytes qint64

PySide2.QtCore.QIODevice. canReadLine ( )
返回类型

bool

返回 true 若可以从设备读取完整数据行;否则返回 false .

注意:没有办法确定是否可以读取的无缓冲设备始终返回 false。

此函数经常被调用结合 readyRead() 信号。

重实现此函数的子类必须调用基实现以便包括内容为 QIODevice ‘s buffer. Example:

def canReadLine(self):
    return buffer.contains('\n') or QIODevice.canReadLine()
											
PySide2.QtCore.QIODevice. channelBytesWritten ( channel , bytes )
参数
  • channel int

  • bytes qint64

PySide2.QtCore.QIODevice. channelReadyRead ( channel )
参数

channel int

PySide2.QtCore.QIODevice. close ( )

首先发射 aboutToClose() , then closes the device and sets its OpenMode to NotOpen 。错误字符串也会被重置。

另请参阅

setOpenMode() OpenMode

PySide2.QtCore.QIODevice. commitTransaction ( )

完成读取事务。

对于顺序设备,在事务期间记录在内部缓冲的所有数据将被丢弃。

PySide2.QtCore.QIODevice. currentReadChannel ( )
返回类型

int

返回当前读取通道的索引。

PySide2.QtCore.QIODevice. currentWriteChannel ( )
返回类型

int

返回当前写入通道的索引。

PySide2.QtCore.QIODevice. errorString ( )
返回类型

unicode

返回人类可读的最后发生的设备错误描述。

另请参阅

setErrorString()

PySide2.QtCore.QIODevice. getChar ( )
返回类型

bool

从设备读取 1 字符并把它存储在 c 。若 c is None ,字符被丢弃。返回 true 当成功时;否则返回 false .

PySide2.QtCore.QIODevice. isOpen ( )
返回类型

bool

返回 true 若设备是打开的;否则返回 false 。设备是打开的若可以读/写。默认情况下,此函数返回 false if openMode() 返回 NotOpen .

另请参阅

openMode() OpenMode

PySide2.QtCore.QIODevice. isReadable ( )
返回类型

bool

返回 true 若可以从设备读取数据;否则返回 false。使用 bytesAvailable() to determine how many bytes can be read.

这是方便的校验函数若 OpenMode 的设备包含 ReadOnly 标志。

另请参阅

openMode() OpenMode

PySide2.QtCore.QIODevice. isSequential ( )
返回类型

bool

返回 true 若此设备是顺序的;否则返回 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.

另一方面,常规文件确实支持随机访问。它们拥有大小和当前位置,且它们还支持在数据流中向后和向前寻址。常规文件是非顺序的。

另请参阅

bytesAvailable()

PySide2.QtCore.QIODevice. isTextModeEnabled ( )
返回类型

bool

返回 true 文本 标志被启用;否则返回 false .

PySide2.QtCore.QIODevice. isTransactionStarted ( )
返回类型

bool

返回 true 若事务在设备上正在进行中,否则 false .

PySide2.QtCore.QIODevice. isWritable ( )
返回类型

bool

返回 true 若可以把数据写入设备;否则返回 false。

这是方便的校验函数若 OpenMode 的设备包含 WriteOnly 标志。

另请参阅

openMode() OpenMode

PySide2.QtCore.QIODevice. open ( mode )
参数

mode OpenMode

返回类型

bool

打开设备并设置其 OpenMode to mode 。返回 true 若成功;否则返回 false . This function should be called from any reimplementations of or other functions that open the device.

另请参阅

openMode() OpenMode

PySide2.QtCore.QIODevice. openMode ( )
返回类型

OpenMode

返回设备被打开的模式;即: ReadOnly or WriteOnly .

另请参阅

setOpenMode() OpenMode

PySide2.QtCore.QIODevice. peek ( maxlen )
参数

maxlen qint64

返回类型

QByteArray

这是重载函数。

窥视最多 maxSize 字节从设备,返回窥视数据作为 QByteArray .

范例:

def isExeFile(file_):
    return file_.peek(2) == "MZ"
											

此函数没有办法报告错误;返回空 QByteArray 可能意味着当前没有数据可供窥视,或发生错误。

另请参阅

read()

PySide2.QtCore.QIODevice. pos ( )
返回类型

qint64

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.

设备的当前读/写位置的内部维护由 QIODevice ,因此重实现此函数不必要。当子类化 QIODevice ,使用 seek() to notify QIODevice 关于设备位置的变化。

PySide2.QtCore.QIODevice. putChar ( c )
参数

c char

返回类型

bool

写入字符 c 到设备。返回 true 当成功时;否则返回 false .

PySide2.QtCore.QIODevice. read ( maxlen )
参数

maxlen qint64

返回类型

QByteArray

这是重载函数。

读取最多 maxSize 字节从设备,并把读取数据返回作为 QByteArray .

此函数没有办法报告错误;返回空 QByteArray 可以意味着目前没有数据可供读取,或发生错误。

PySide2.QtCore.QIODevice. readAll ( )
返回类型

QByteArray

从设备读取所有剩余数据,并将其作为字节数组返回。

此函数没有办法报告错误;返回空 QByteArray 可以意味着目前没有数据可供读取,或发生错误。

PySide2.QtCore.QIODevice. readChannelCount ( )
返回类型

int

返回可用的读取通道数若设备是打开的;否则返回 0。

PySide2.QtCore.QIODevice. readChannelFinished ( )
PySide2.QtCore.QIODevice. readData ( maxlen )
参数

maxlen qint64

返回类型

PyObject

读取到 maxSize 字节从设备到 data ,并返回读取字节数;返回 -1 若发生错误。

若没有字节要读取且从不会有更多字节可用 (范例包括:套接字被关闭、管道被关闭、子进程已完成),此函数返回 -1。

此函数被调用由 QIODevice 。重实现此函数,当创建子类为 QIODevice .

当重实现此函数时,此函数在返回之前读取所有要求数据是很重要的。这是必需的为 QDataStream 能够在类中运转。 QDataStream 假定所有请求信息被读取,因此,不会重试读取若存在问题。

可以在 maxSize 为 0 的情况下调用 此函数,用于履行读取后操作。

PySide2.QtCore.QIODevice. readLine ( [ maxlen=0 ] )
参数

maxlen qint64

返回类型

QByteArray

这是重载函数。

从设备读取行,但不超过 maxSize 字符,并以字节数组形式返回结果。

此函数没有办法报告错误;返回空 QByteArray 可以意味着目前没有数据可供读取,或发生错误。

PySide2.QtCore.QIODevice. readLineData ( maxlen )
参数

maxlen qint64

返回类型

PyObject

读取到 maxSize 字符到 data 并返回读取的字符数。

此函数被调用由 readLine() , and provides its base implementation, using getChar() . Buffered devices can improve the performance of readLine() by reimplementing this function.

readLine() appends a ‘\0’ byte to data ; does not need to do this.

若重实现此函数,小心返回正确值:它应返回在这一行中读取的字节数 (包括终止换行符),或 0 若此时没有行要读取。若发生错误,它应返回 -1,当且仅当没有字节要读取时。读取超过 EOF 认为出错。

PySide2.QtCore.QIODevice. readyRead ( )
PySide2.QtCore.QIODevice. reset ( )
返回类型

bool

寻址随机访问设备输入起始。成功返回 true;否则返回 false (例如:若设备未被打开)。

注意,当使用 QTextStream QFile , calling on the QFile 将不会有预期结果,因为 QTextStream 缓冲文件。使用 seek() function instead.

另请参阅

seek()

PySide2.QtCore.QIODevice. rollbackTransaction ( )

回滚读取事务。

将输入流还原到点对于 startTransaction() call. This function is commonly used to rollback the transaction when an incomplete read was detected prior to committing the transaction.

PySide2.QtCore.QIODevice. seek ( pos )
参数

pos qint64

返回类型

bool

对于随机访问设备,此函数将当前位置设为 pos ,返回 true 当成功时,或 false 若发生错误。对于顺序设备,默认行为是产生警告并返回 false。

当子类化 QIODevice , you must call at the start of your function to ensure integrity with QIODevice ‘s built-in buffer.

PySide2.QtCore.QIODevice. setCurrentReadChannel ( channel )
参数

channel int

设置当前读取通道为 QIODevice 到给定 channel 。当前输入通道用于函数 read() , readAll() , readLine() ,和 getChar() . It also determines which channel triggers QIODevice 以发射 readyRead() .

PySide2.QtCore.QIODevice. setCurrentWriteChannel ( channel )
参数

channel int

设置当前写入通道为 QIODevice 到给定 channel 。当前输出通道用于函数 write() , putChar() . It also determines which channel triggers QIODevice 以发射 bytesWritten() .

PySide2.QtCore.QIODevice. setErrorString ( errorString )
参数

errorString – unicode

将最后发生的设备错误的人类可读描述设为 str .

另请参阅

errorString()

PySide2.QtCore.QIODevice. setOpenMode ( openMode )
参数

openMode OpenMode

设置 OpenMode 为设备到 openMode 。调用此函数以设置打开模式,若设备打开后标志有变化。

另请参阅

openMode() OpenMode

PySide2.QtCore.QIODevice. setTextModeEnabled ( enabled )
参数

enabled bool

enabled 为 true,此函数设置 文本 标志在设备;否则 文本 标志被移除。此特征很有用,对于提供自定义行尾处理的类而言在 QIODevice .

IO 设备应被打开,在调用此函数之前。

PySide2.QtCore.QIODevice. size ( )
返回类型

qint64

对于打开的随机访问设备,此函数返回设备的大小。对于打开的顺序设备, bytesAvailable() 被返回。

若设备是关闭的,返回尺寸不会反映设备的实际大小。

PySide2.QtCore.QIODevice. skip ( maxSize )
参数

maxSize qint64

返回类型

qint64

跳过直到 maxSize 字节从设备。返回实际跳过字节数,或 -1 当出错时。

此函数不等待,且仅丢弃已可供读取的数据。

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() and peek() behavior.

此函数适于所有设备,包括顺序设备无法 seek() . It is optimized to skip unwanted data after a peek() 调用。

For random-access devices, can be used to seek forward from the current position. Negative maxSize 值是不允许的。

PySide2.QtCore.QIODevice. startTransaction ( )

在设备上启动新的读取事务。

在读取操作的序列中,定义可还原点。对于顺序设备,读取数据将在内部被复制,以在读取不完整的情况下允许还原。对于随机访问设备,此函数保存当前位置。调用 commitTransaction() or rollbackTransaction() to finish the transaction.

注意

嵌套事务不被支持。

PySide2.QtCore.QIODevice. ungetChar ( c )
参数

c char

放置字符 c back into the device, and decrements the current position unless the position is 0. This function is usually called to “undo” a getChar() operation, such as when writing a backtracking parser.

c 先前未从设备读取,行为未定义。

注意

此函数不可用,当事务正在进行时。

PySide2.QtCore.QIODevice. waitForBytesWritten ( msecs )
参数

msecs int

返回类型

bool

对于缓冲设备,此函数等待直到缓冲写入数据负载已写入设备且 bytesWritten() signal has been emitted, or until msecs 毫秒已过去。若 msecs 为 -1,此函数不会超时。对于无缓冲设备,会立即返回。

返回 true 若数据负载已写入设备;否则返回 false (即:若操作超时或发生错误)。

可以在没有事件循环的情况下操作此函数。它很有用,当编写非 GUI 应用程序和在非 GUI 线程中履行 I/O 操作时。

若调用来自的槽有连接到 bytesWritten() signal, bytesWritten() will not be reemitted.

重新实现此函数能为自定义设备提供阻塞 API。默认实现什么都不做,并返回 false .

警告

从主 GUI 线程调用此函数可能导致用户界面被冻结。

PySide2.QtCore.QIODevice. waitForReadyRead ( msecs )
参数

msecs int

返回类型

bool

阻塞直到有新的数据可供读取且 readyRead() signal has been emitted, or until msecs 毫秒已过去。若 msecs 为 -1,此函数不会超时。

返回 true 若新数据可用于读取;否则返回 false (若操作超时或发生错误)。

可以在没有事件循环的情况下操作此函数。它很有用,当编写非 GUI 应用程序和在非 GUI 线程中履行 I/O 操作时。

若调用来自的槽有连接到 readyRead() signal, readyRead() will not be reemitted.

重新实现此函数能为自定义设备提供阻塞 API。默认实现什么都不做,并返回 false .

警告

从主 GUI 线程调用此函数可能导致用户界面被冻结。

PySide2.QtCore.QIODevice. write ( data )
参数

data QByteArray

返回类型

qint64

PySide2.QtCore.QIODevice. writeChannelCount ( )
返回类型

int

返回可用写入通道数,若设备是打开的;否则返回 0。

PySide2.QtCore.QIODevice. writeData ( data , len )
参数
  • data – str

  • len qint64

返回类型

qint64

写入直到 maxSize 字节来自 data 到设备。返回写入字节数,或 -1 若发生错误。

此函数被调用由 QIODevice 。重实现此函数,当创建子类为 QIODevice .

当重实现此函数时,此函数在返回前写入所有可用数据很重要。这是必需的为使 QDataStream 能够在类中运转。 QDataStream 假定所有信息已写入,因此不会试着再写入若存在问题。

另请参阅

read() write()