QIODevice Class Reference

[ QtCore module]

The QIODevice class is the base interface class of all I/O devices in Qt. 更多...

继承 QObject .

Inherited by QAbstractSocket , QBuffer , QFile , QLocalSocket , QNetworkReply and QProcess .

类型

方法

Qt Signals


详细描述

The QIODevice class is the base interface class of all I/O devices in Qt.

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 can not 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 () 必须被调用以设置正确 OpenMode (譬如 ReadOnly or ReadWrite ). You can then write to the device with write () or putChar (), and read by calling either read (), readLine (),或 readAll ()。调用 close () when you are done with the 设备。

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

可以使用 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 emits the 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 , are asynchronous. This means that I/O functions such as write () 或 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:

Calling these functions from the main, GUI thread, may cause your user interface to freeze. Example:

 QProcess gzip;
 gzip.start("gzip", QStringList() << "-c");
 if (!gzip.waitForStarted())
     return false;
 gzip.write("uncompressed data");
 QByteArray compressed;
 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 () 和 writeData () functions. QIODevice uses these functions to implement all its convenience functions, such as getChar (), readLine () 和 write (). QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData () 被调用。

Some subclasses, such as QFile and QTcpSocket , 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 like getChar () 和 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.


类型文档编制

QIODevice.OpenModeFlag

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

常量 描述
QIODevice.NotOpen 0x0000 设备未打开。
QIODevice.ReadOnly 0x0001 打开设备以供读取。
QIODevice.WriteOnly 0x0002 The device is open for writing.
QIODevice.ReadWrite ReadOnly | WriteOnly The device is open for reading and writing.
QIODevice.Append 0x0004 The device is opened in append mode, so that all data is written to the end of the file.
QIODevice.Truncate 0x0008 If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
QIODevice.Text 0x0010 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 0x0020 绕过任何设备缓冲。

某些标志,如 Unbuffered and Truncate , 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 support Unbuffered mode, and limitations in the native API prevent QFile from supporting Unbuffered 在 Windows。

OpenMode 类型是 typedef 对于 QFlags <OpenModeFlag>. It stores an OR combination of OpenModeFlag values.


方法文档编制

QIODevice.__init__ ( self )

构造 QIODevice 对象。

QIODevice.__init__ ( self , QObject   parent )

parent argument, if not None, causes self to be owned by Qt instead of PyQt.

构造 QIODevice object with the given parent .

bool QIODevice.atEnd ( self )

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 returns false.

For some devices, atEnd() 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 files on Unix and Mac OS X, or console input / stdin 在所有平台)。

另请参阅 bytesAvailable (), read (),和 isSequential ().

int QIODevice.bytesAvailable ( self )

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 QIODevices' buffer. 范例:

 long CustomDevice.bytesAvailable() const
 {
     return buffer.size() + QIODevice.bytesAvailable();
 }
			

另请参阅 bytesToWrite (), readyRead (),和 isSequential ().

int QIODevice.bytesToWrite ( self )

For buffered devices, this function returns the number of bytes waiting to be written. For devices with no buffer, this function returns 0.

另请参阅 bytesAvailable (), bytesWritten (),和 isSequential ().

bool QIODevice.canReadLine ( self )

Returns true if a complete line of data can be read from the device; otherwise returns false.

Note that unbuffered devices, which have no way of determining what can be read, always return false.

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

Subclasses that reimplement this function must call the base implementation in order to include the contents of the QIODevice 的缓冲。范例:

 bool CustomDevice.canReadLine() const
 {
     return buffer.contains('\n') || QIODevice.canReadLine();
 }
			

另请参阅 readyRead () 和 readLine ().

QIODevice.close ( self )

首先发射 aboutToClose (), then closes the device and sets its OpenMode to NotOpen . The error string is also reset.

另请参阅 setOpenMode () 和 OpenMode .

QString QIODevice.errorString ( self )

Returns a human-readable description of the last device error that occurred.

另请参阅 setErrorString ().

(bool, str  c ) QIODevice.getChar ( self )

从设备读取 1 字符并把它存储在 c . 若 c is 0, the character is discarded. Returns true on success; otherwise returns false.

另请参阅 read (), putChar (),和 ungetChar ().

bool QIODevice.isOpen ( self )

Returns true if the device is open; otherwise returns false. A device is open if it can be read from and/or written to. By default, this function returns false if openMode () 返回 NotOpen .

另请参阅 openMode () and OpenMode .

bool QIODevice.isReadable ( self )

Returns true if data can be read from the device; otherwise returns false. Use bytesAvailable () to determine how many bytes can be read.

这是方便的校验函数若 OpenMode of the device contains the ReadOnly 标志。

另请参阅 openMode () and OpenMode .

bool QIODevice.isSequential ( self )

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.

QIODevice 实现 returns false.

另请参阅 bytesAvailable ().

bool QIODevice.isTextModeEnabled ( self )

返回 true 若 文本 flag is enabled; otherwise returns false.

另请参阅 setTextModeEnabled ().

bool QIODevice.isWritable ( self )

Returns true if data can be written to the device; otherwise returns false.

这是方便的校验函数若 OpenMode of the device contains the WriteOnly 标志。

另请参阅 openMode () and OpenMode .

bool QIODevice.open ( self , OpenMode   mode )

打开设备并设置其 OpenMode to mode . Returns true if successful; otherwise returns false. This function should be called from any reimplementations of open() or other functions that open the device.

另请参阅 openMode () and OpenMode .

OpenMode QIODevice.openMode ( self )

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

另请参阅 setOpenMode () 和 OpenMode .

QByteArray QIODevice.peek ( self , int  maxlen )

读取最多 maxSize 字节从设备到 data ,无副作用 (即:若调用 read () after peek(), you will get the same data). Returns the number of bytes read. If an error occurs, such as when attempting to peek a device opened in WriteOnly mode, this function returns -1.

0 is returned when no more data is available for reading.

范例:

 bool isExeFile(QFile *file)
 {
     char buf[2];
     if (file->peek(buf, sizeof(buf)) == sizeof(buf))
         return (buf[0] == 'M' && buf[1] == 'Z');
     return false;
 }
			

该函数在 Qt 4.1 引入。

另请参阅 read ().

int QIODevice.pos ( self )

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 subclassing QIODevice ,使用 QIODevice.seek () to notify QIODevice about changes in the device position.

另请参阅 isSequential () 和 seek ().

bool QIODevice.putChar ( self , str  c )

写入字符 c to the device. Returns true on success; otherwise returns false.

另请参阅 write (), getChar (),和 ungetChar ().

str QIODevice.read ( self , int  maxlen )

读取最多 maxSize 字节从设备到 data , and returns the number of bytes read. If an error occurs, such as when attempting to read from a device opened in WriteOnly mode, this function returns -1.

0 is returned when no more data is available for reading. However, reading past the end of the stream is considered an error, so this function returns -1 in those cases (that is, reading on a closed socket or after a process has died).

另请参阅 readData (), readLine (),和 write ().

QByteArray QIODevice.readAll ( self )

这是重载函数。

Reads all available data from the device, and returns it as a QByteArray .

此函数没有办法报告错误;返回空 QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

str QIODevice.readData ( self , int  maxlen )

This method is abstract and should be reimplemented in any sub-class.

读取到 maxSize 字节从设备到 data , 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.

此函数被调用由 QIODevice . Reimplement this function when creating a subclass of QIODevice .

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.

另请参阅 read (), readLine (),和 writeData ().

str QIODevice.readLine ( self , int  maxlen  = 0)

This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data , and returns the number of bytes read. If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns the length of what could be read, or -1 if nothing was read.

A terminating '\0' byte is always appended to data , so maxSize must be larger than 1.

Data is read until either of the following conditions are met:

For example, the following code reads a line of characters from a file:

 QFile file("box.txt");
 if (file.open(QFile.ReadOnly)) {
     char buf[1024];
     long lineLength = file.readLine(buf, sizeof(buf));
     if (lineLength != -1) {
         // the line is available in buf
     }
 }
			

The newline character ('\n') is included in the buffer. If a newline is not encountered before maxSize - 1 bytes are read, a newline will not be inserted into the buffer. On windows newline characters are replaced with '\n'.

此函数调用 readLineData (), which is implemented using repeated calls to getChar (). You can provide a more efficient implementation by reimplementing readLineData () in your own 子类。

另请参阅 getChar (), read (),和 write ().

str QIODevice.readLineData ( self , int  maxlen )

读取到 maxSize 字符到 data and returns the number of characters read.

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

readLine () appends a '\0' byte to data ; readLineData() 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.

bool QIODevice.reset ( self )

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 QFile , calling reset() on the QFile will not have the expected result because QTextStream buffers the file. Use the QTextStream.seek () function instead.

另请参阅 seek ().

bool QIODevice.seek ( self , int  pos )

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 do nothing and return false.

When subclassing QIODevice , you must call QIODevice.seek() at the start of your function to ensure integrity with QIODevice 's built-in buffer. The base implementation always returns true.

另请参阅 pos () 和 isSequential ().

QIODevice.setErrorString ( self , QString  errorString )

Sets the human readable description of the last device error that occurred to str .

另请参阅 errorString ().

QIODevice.setOpenMode ( self , OpenMode   openMode )

设置 OpenMode of the device to openMode . Call this function to set the open mode if the flags change after the device has been opened.

另请参阅 openMode () and OpenMode .

QIODevice.setTextModeEnabled ( self , bool  enabled )

enabled 为 true,此函数设置 文本 flag on the device; otherwise the 文本 flag is removed. This feature is useful for classes that provide custom end-of-line handling on a QIODevice .

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

另请参阅 isTextModeEnabled (), open (),和 setOpenMode ().

int QIODevice.size ( self )

For open random-access devices, this function returns the size of the device. For open sequential devices, bytesAvailable () 是 returned.

If the device is closed, the size returned will not reflect the actual size of the device.

另请参阅 isSequential () 和 pos ().

QIODevice.ungetChar ( self , str  c )

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" a getChar () operation, such as when writing a backtracking parser.

c was not previously read from the device, the behavior is undefined.

bool QIODevice.waitForBytesWritten ( self , int  msecs )

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 until msecs 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 returns false (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.

警告: Calling this function from the main (GUI) thread might cause your user interface to freeze.

另请参阅 waitForReadyRead ().

bool QIODevice.waitForReadyRead ( self , int  msecs )

阻塞直到有新的数据可供读取且 readyRead () signal has been emitted, or until msecs 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.

警告: Calling this function from the main (GUI) thread might cause your user interface to freeze.

另请参阅 waitForBytesWritten ().

int QIODevice.write ( self , QByteArray   data )

写入最多 maxSize 字符的数据从 data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

另请参阅 read () 和 writeData ().

int QIODevice.writeData ( self , str  data )

This method is abstract and should be reimplemented in any sub-class.

写入直到 maxSize 字节来自 data 到 device. Returns the number of bytes written, or -1 if an error occurred.

此函数被调用由 QIODevice . Reimplement this function when creating a subclass of QIODevice .

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.

另请参阅 read () 和 write ().


Qt Signal Documentation

void aboutToClose ()

This is the default overload of this signal.

This signal is emitted when the device is about to close. Connect this signal if you have operations that need to be performed before the device closes (e.g., if you have data in a separate buffer that needs to be written to the device).

void bytesWritten (qint64)

This is the default overload of this signal.

This signal is emitted every time a payload of data has been written to the device. The bytes argument is set to the number of bytes that were written in this payload.

bytesWritten() is not emitted recursively; if you reenter the event loop or call waitForBytesWritten () inside a slot connected to the bytesWritten() signal, the signal will not be reemitted (although waitForBytesWritten () may still return true).

另请参阅 readyRead ().

void readChannelFinished ()

This is the default overload of this signal.

This signal is emitted when the input (reading) stream is closed in this device. It is emitted as soon as the closing is detected, which means that there might still be data available for reading with read ().

该函数在 Qt 4.4 引入。

另请参阅 atEnd () 和 read ().

void readyRead ()

This is the default overload of this signal.

This signal is emitted once every time new data is available for reading from the device. It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.

readyRead() is not emitted recursively; if you reenter the event loop or call waitForReadyRead () inside a slot connected to the readyRead() signal, the signal will not be reemitted (although waitForReadyRead () may still return true).

注意: 开发者实现的类派生自 QIODevice : you should always emit readyRead() when new data has arrived (do not emit it only because there's data still to be read in your buffers). Do not emit readyRead() in other conditions.

另请参阅 bytesWritten ().