内容表

上一话题

QTextEncoder

下一话题

QTextStreamManipulator

QTextStream

QTextStream class provides a convenient interface for reading and writing text. 更多

Inheritance diagram of PySide2.QtCore.QTextStream

概要

函数

详细描述

QTextStream can operate on a QIODevice QByteArray QString . Using QTextStream ‘s streaming operators, you can conveniently read and write words, lines and numbers. For generating text, QTextStream supports formatting options for field padding and alignment, and formatting of numbers. Example:

data = QFile("output.txt")
if data.open(QFile.WriteOnly | QFile.Truncate):
    out = QTextStream(&data)
    out << "Result: " << qSetFieldWidth(10) << left << 3.14 << 2.7
    # writes "Result: 3.14      2.7       "
											

It’s also common to use QTextStream to read console input and write console output. QTextStream is locale aware, and will automatically decode standard input using the correct codec. Example:

stream = QTextStream(sys.stdin.fileno())
while(True):
    line = stream.readLine()
    if line.isNull():
        break;
											

Besides using QTextStream ‘s constructors, you can also set the device or string QTextStream operates on by calling setDevice() or setString() . You can seek to a position by calling seek() ,和 atEnd() will return true when there is no data left to be read. If you call flush() , QTextStream will empty all data from its write buffer into the device and call flush() on the device.

内部, QTextStream uses a Unicode based buffer, and QTextCodec is used by QTextStream to automatically support different character sets. By default, codecForLocale() is used for reading and writing, but you can also set the codec by calling setCodec() . Automatic Unicode detection is also supported. When this feature is enabled (the default behavior), QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and switch to the appropriate UTF codec when reading. QTextStream does not write a BOM by default, but you can enable this by calling setGenerateByteOrderMark (true). When QTextStream operates on a QString directly, the codec is disabled.

There are three general ways to use QTextStream when reading text files:

  • Chunk by chunk, by calling readLine() or readAll() .

  • Word by word. QTextStream supports streaming into QString s, QByteArray s and char* buffers. Words are delimited by space, and leading white space is automatically skipped.

  • Character by character, by streaming into QChar or char types. This method is often used for convenient input handling when parsing files, independent of character encoding and end-of-line semantics. To skip white space, call skipWhiteSpace() .

Since the text stream uses a buffer, you should not read from the stream using the implementation of a superclass. For instance, if you have a QFile and read from it directly using readLine() instead of using the stream, the text stream’s internal position will be out of sync with the file’s position.

By default, when reading numbers from a stream of text, QTextStream will automatically detect the number’s base representation. For example, if the number starts with “0x”, it is assumed to be in hexadecimal form. If it starts with the digits 1-9, it is assumed to be in decimal form, and so on. You can set the integer base, thereby disabling the automatic detection, by calling setIntegerBase() 。范例:

in_ = QTextStream("0x50 0x20")
firstNumber = 0
secondNumber = 0
in_ >> firstNumber             # firstNumber == 80
in_ >> dec >> secondNumber     # secondNumber == 0
ch = None
in_ >> ch                      # ch == 'x'
											

QTextStream supports many formatting options for generating text. You can set the field width and pad character by calling setFieldWidth() and setPadChar() 。使用 setFieldAlignment() to set the alignment within each field. For real numbers, call setRealNumberNotation() and setRealNumberPrecision() to set the notation ( SmartNotation , ScientificNotation , FixedNotation ) and precision in digits of the generated number. Some extra number formatting options are also available through setNumberFlags() .

<iostream> in the standard C++ library, QTextStream also defines several global manipulator functions:

操作符

描述

bin

如同 setIntegerBase (2).

oct

如同 setIntegerBase (8).

dec

如同 setIntegerBase (10).

hex

如同 setIntegerBase (16).

showbase

如同 setNumberFlags ( numberFlags() | ShowBase ).

forcesign

如同 setNumberFlags ( numberFlags() | ForceSign ).

forcepoint

如同 setNumberFlags ( numberFlags() | ForcePoint ).

noshowbase

如同 setNumberFlags ( numberFlags() & ~ ShowBase ).

noforcesign

如同 setNumberFlags ( numberFlags() & ~ ForceSign ).

noforcepoint

如同 setNumberFlags ( numberFlags() & ~ ForcePoint ).

uppercasebase

如同 setNumberFlags ( numberFlags() | UppercaseBase ).

uppercasedigits

如同 setNumberFlags ( numberFlags() | UppercaseDigits ).

lowercasebase

如同 setNumberFlags ( numberFlags() & ~ UppercaseBase ).

lowercasedigits

如同 setNumberFlags ( numberFlags() & ~ UppercaseDigits ).

fixed

如同 setRealNumberNotation ( FixedNotation ).

scientific

如同 setRealNumberNotation ( ScientificNotation ).

left

如同 setFieldAlignment ( AlignLeft ).

right

如同 setFieldAlignment ( AlignRight ).

center

如同 setFieldAlignment ( AlignCenter ).

endl

Same as operator<<(‘\n’) and flush() .

flush

如同 flush() .

reset

如同 reset() .

ws

如同 skipWhiteSpace() .

bom

如同 setGenerateByteOrderMark (true)。

In addition, Qt provides three global manipulators that take a parameter: qSetFieldWidth() , qSetPadChar() ,和 qSetRealNumberPrecision() .

class QTextStream

QTextStream(array[, openMode=QIODevice.ReadWrite])

QTextStream(device)

param openMode

OpenMode

param array

QByteArray

param device

QIODevice

构造 QTextStream . Before you can use it for reading or writing, you must assign a device or a string.

另请参阅

setDevice() setString()

构造 QTextStream that operates on array ,使用 openMode to define the open mode. Internally, the array is wrapped by a QBuffer .

构造 QTextStream that operates on device .

PySide2.QtCore.QTextStream. RealNumberNotation

This enum specifies which notations to use for expressing float and double as strings.

常量

描述

QTextStream.ScientificNotation

Scientific notation ( printf() ’s %e 标志)。

QTextStream.FixedNotation

Fixed-point notation ( printf() ’s %f 标志)。

QTextStream.SmartNotation

Scientific or fixed-point notation, depending on which makes most sense ( printf() ’s %g 标志)。

PySide2.QtCore.QTextStream. FieldAlignment

This enum specifies how to align text in fields when the field is wider than the text that occupies it.

常量

描述

QTextStream.AlignLeft

Pad on the right side of fields.

QTextStream.AlignRight

Pad on the left side of fields.

QTextStream.AlignCenter

Pad on both sides of field.

QTextStream.AlignAccountingStyle

Same as , except that the sign of a number is flush left.

PySide2.QtCore.QTextStream. Status

此枚举描述文本流的当前状态。

常量

描述

QTextStream.Ok

The text stream is operating normally.

QTextStream.ReadPastEnd

The text stream has read past the end of the data in the underlying device.

QTextStream.ReadCorruptData

The text stream has read corrupt data.

QTextStream.WriteFailed

The text stream cannot write to the underlying device.

另请参阅

status()

PySide2.QtCore.QTextStream. NumberFlag

This enum specifies various flags that can be set to affect the output of integers, float s, and double s.

常量

描述

QTextStream.ShowBase

Show the base as a prefix if the base is 16 (“0x”), 8 (“0”), or 2 (“0b”).

QTextStream.ForcePoint

Always put the decimal separator in numbers, even if there are no decimals.

QTextStream.ForceSign

Always put the sign in numbers, even for positive numbers.

QTextStream.UppercaseBase

Use uppercase versions of base prefixes (“0X”, “0B”).

QTextStream.UppercaseDigits

Use uppercase letters for expressing digits 10 to 35 instead of lowercase.

另请参阅

setNumberFlags()

PySide2.QtCore.QTextStream. atEnd ( )
返回类型

bool

返回 true if there is no more data to be read from the QTextStream ;否则返回 false . This is similar to, but not the same as calling atEnd() , as QTextStream also takes into account its internal Unicode buffer.

PySide2.QtCore.QTextStream. autoDetectUnicode ( )
返回类型

bool

返回 true if automatic Unicode detection is enabled, otherwise returns false . Automatic Unicode detection is enabled by default.

PySide2.QtCore.QTextStream. codec ( )
返回类型

QTextCodec

Returns the codec that is current assigned to the stream.

PySide2.QtCore.QTextStream. device ( )
返回类型

QIODevice

返回被当前设备关联的 QTextStream ,或 None 若没有设备被赋值。

PySide2.QtCore.QTextStream. fieldAlignment ( )
返回类型

FieldAlignment

Returns the current field alignment.

PySide2.QtCore.QTextStream. fieldWidth ( )
返回类型

int

Returns the current field width.

另请参阅

setFieldWidth()

PySide2.QtCore.QTextStream. flush ( )

Flushes any buffered data waiting to be written to the device.

QTextStream operates on a string, this function does nothing.

PySide2.QtCore.QTextStream. generateByteOrderMark ( )
返回类型

bool

返回 true if QTextStream is set to generate the UTF BOM (Byte Order Mark) when using a UTF codec; otherwise returns false . UTF BOM generation is set to false by default.

PySide2.QtCore.QTextStream. integerBase ( )
返回类型

int

Returns the current base of integers. 0 means that the base is detected when reading, or 10 (decimal) when generating numbers.

PySide2.QtCore.QTextStream. locale ( )
返回类型

QLocale

Returns the locale for this stream. The default locale is C.

另请参阅

setLocale()

PySide2.QtCore.QTextStream. numberFlags ( )
返回类型

NumberFlags

Returns the current number flags.

PySide2.QtCore.QTextStream. __lshift__ ( s )
参数

s – unicode

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( i )
参数

i – long

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( i )
参数

i long

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( ch )
参数

ch QChar

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( m )
参数

m QTextStreamManipulator

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( ch )
参数

ch char

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( array )
参数

array QByteArray

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( arg__2 )
参数

arg__2 QDomNode

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( arg__2 )
参数

arg__2 QSplitter

返回类型

QTextStream

注意

此函数被弃用。

PySide2.QtCore.QTextStream. __lshift__ ( s )
参数

s QStringRef

返回类型

QTextStream

PySide2.QtCore.QTextStream. __lshift__ ( f )
参数

f double

返回类型

QTextStream

PySide2.QtCore.QTextStream. __rshift__ ( array )
参数

array QByteArray

返回类型

QTextStream

PySide2.QtCore.QTextStream. __rshift__ ( arg__2 )
参数

arg__2 QSplitter

返回类型

QTextStream

注意

此函数被弃用。

PySide2.QtCore.QTextStream. padChar ( )
返回类型

QChar

Returns the current pad character.

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

qint64

Returns the device position corresponding to the current position of the stream, or -1 if an error occurs (e.g., if there is no device or string, or if there’s a device error).

因为 QTextStream is buffered, this function may have to seek the device to reconstruct a valid device position. This operation can be expensive, so you may want to avoid calling this function in a tight loop.

另请参阅

seek()

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

maxlen qint64

返回类型

unicode

读取最多 maxlen characters from the stream, and returns the data read as a QString .

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

unicode

Reads the entire content of the stream, and returns it as a QString . Avoid this function when working on large files, as it will consume a significant amount of memory.

调用 readLine() is better if you do not know how much data is available.

另请参阅

readLine()

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

maxlen qint64

返回类型

unicode

Reads one line of text from the stream, and returns it as a QString . The maximum allowed line length is set to maxlen . If the stream contains lines longer than this, then the lines will be split after maxlen characters and returned in parts.

maxlen is 0, the lines can be of any length.

The returned line has no trailing end-of-line characters (“\n” or “\r\n”), so calling trimmed() can be unnecessary.

If the stream has read to the end of the file, will return a null QString . For strings, or for devices that support it, you can explicitly test for the end of the stream using atEnd() .

PySide2.QtCore.QTextStream. realNumberNotation ( )
返回类型

RealNumberNotation

Returns the current real number notation.

PySide2.QtCore.QTextStream. realNumberPrecision ( )
返回类型

int

Returns the current real number precision, or the number of fraction digits QTextStream will write when generating real numbers.

PySide2.QtCore.QTextStream. reset ( )

Resets QTextStream ‘s formatting options, bringing it back to its original constructed state. The device, string and any buffered data is left untouched.

PySide2.QtCore.QTextStream. resetStatus ( )

Resets the status of the text stream.

另请参阅

Status status() setStatus()

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

pos qint64

返回类型

bool

Seeks to the position pos in the device. Returns true 当成功时;否则返回 false .

PySide2.QtCore.QTextStream. setAutoDetectUnicode ( enabled )
参数

enabled bool

enabled is true, QTextStream will attempt to detect Unicode encoding by peeking into the stream data to see if it can find the UTF-8, UTF-16, or UTF-32 Byte Order Mark (BOM). If this mark is found, QTextStream will replace the current codec with the UTF codec.

This function can be used together with setCodec() . It is common to set the codec to UTF-8, and then enable UTF-16 detection.

PySide2.QtCore.QTextStream. setCodec ( codec )
参数

codec QTextCodec

Sets the codec for this stream to codec . The codec is used for decoding any data that is read from the assigned device, and for encoding any data that is written. By default, codecForLocale() is used, and automatic unicode detection is enabled.

QTextStream operates on a string, this function does nothing.

警告

If you call this function while the text stream is reading from an open sequential socket, the internal buffer may still contain text decoded using the old codec.

PySide2.QtCore.QTextStream. setCodec ( codecName )
参数

codecName – str

Sets the codec for this stream to the QTextCodec 为指定编码通过 codecName 。常见值对于 codecName include “ISO 8859-1”, “UTF-8”, and “UTF-16”. If the encoding isn’t recognized, nothing happens.

范例:

out = QTextStream(file)
out.setCodec("UTF-8")
											
PySide2.QtCore.QTextStream. setDevice ( device )
参数

device QIODevice

把当前设备设为 device . If a device has already been assigned, QTextStream will call flush() before the old device is replaced.

注意

This function resets locale to the default locale (‘C’) and codec to the default codec, codecForLocale() .

另请参阅

device() setString()

PySide2.QtCore.QTextStream. setFieldAlignment ( alignment )
参数

alignment FieldAlignment

Sets the field alignment to mode . When used together with setFieldWidth() , this function allows you to generate formatted output with text aligned to the left, to the right or center aligned.

PySide2.QtCore.QTextStream. setFieldWidth ( width )
参数

width int

Sets the current field width to width 。若 width is 0 (the default), the field width is equal to the length of the generated text.

注意

The field width applies to every element appended to this stream after this function has been called (e.g., it also pads endl). This behavior is different from similar classes in the STL, where the field width only applies to the next element.

PySide2.QtCore.QTextStream. setGenerateByteOrderMark ( generate )
参数

generate bool

generate is true and a UTF codec is used, QTextStream will insert the BOM (Byte Order Mark) before any data has been written to the device. If generate is false, no BOM will be inserted. This function must be called before any data is written. Otherwise, it does nothing.

另请参阅

generateByteOrderMark() bom()

PySide2.QtCore.QTextStream. setIntegerBase ( base )
参数

base int

Sets the base of integers to base , both for reading and for generating numbers. base can be either 2 (binary), 8 (octal), 10 (decimal) or 16 (hexadecimal). If base is 0, QTextStream will attempt to detect the base by inspecting the data on the stream. When generating numbers, QTextStream assumes base is 10 unless the base has been set explicitly.

PySide2.QtCore.QTextStream. setLocale ( locale )
参数

locale QLocale

Sets the locale for this stream to locale . The specified locale is used for conversions between numbers and their string representations.

The default locale is C and it is a special case - the thousands group separator is not used for backward compatibility reasons.

另请参阅

locale()

PySide2.QtCore.QTextStream. setNumberFlags ( flags )
参数

flags NumberFlags

Sets the current number flags to flags . flags is a set of flags from the NumberFlag enum, and describes options for formatting generated code (e.g., whether or not to always write the base or sign of a number).

PySide2.QtCore.QTextStream. setPadChar ( ch )
参数

ch QChar

Sets the pad character to ch . The default value is the ASCII space character (‘ ‘), or QChar (0x20). This character is used to fill in the space in fields when generating text.

范例:

s = QString()
out = QTextStream(s)
out.setFieldWidth(10)
out.setFieldAlignment(QTextStream::AlignCenter)
out.setPadChar('-')
out << "Qt" << "rocks!"
											

字符串 s contains:

----Qt------rocks!--
											
PySide2.QtCore.QTextStream. setRealNumberNotation ( notation )
参数

notation RealNumberNotation

Sets the real number notation to notation ( SmartNotation , FixedNotation , ScientificNotation ). When reading and generating numbers, QTextStream uses this value to detect the formatting of real numbers.

PySide2.QtCore.QTextStream. setRealNumberPrecision ( precision )
参数

precision int

Sets the precision of real numbers to precision . This value describes the number of fraction digits QTextStream should write when generating real numbers.

The precision cannot be a negative value. The default value is 6.

PySide2.QtCore.QTextStream. setStatus ( status )
参数

status Status

Sets the status of the text stream to the status 给定。

Subsequent calls to are ignored until resetStatus() 被调用。

另请参阅

Status status() resetStatus()

PySide2.QtCore.QTextStream. skipWhiteSpace ( )

Reads and discards whitespace from the stream until either a non-space character is detected, or until atEnd() returns true. This function is useful when reading a stream character by character.

Whitespace characters are all characters for which isSpace() 返回 true .

另请参阅

operator>>()

PySide2.QtCore.QTextStream. status ( )
返回类型

Status

返回文本流的状态。

另请参阅

Status setStatus() resetStatus()

PySide2.QtCore.QTextStream. string ( )
返回类型

unicode

Returns the current string assigned to the QTextStream ,或 None if no string has been assigned.

另请参阅

setString() device()