QTextStream¶
The
QTextStream
class provides a convenient interface for reading and writing text. More…
Synopsis¶
Functions¶
def
__lshift__
(, arg__2)def
__lshift__
(, arg__2)def
__lshift__
(, m)def
__lshift__
(array)def
__lshift__
(ch)def
__lshift__
(ch)def
__lshift__
(f)def
__lshift__
(i)def
__lshift__
(i)def
__lshift__
(s)def
__lshift__
(s)def
__rshift__
(, arg__2)def
__rshift__
(array)def
atEnd
()def
autoDetectUnicode
()def
codec
()def
device
()def
fieldAlignment
()def
fieldWidth
()def
flush
()def
generateByteOrderMark
()def
integerBase
()def
locale
()def
numberFlags
()def
padChar
()def
pos
()def
read
(maxlen)def
readAll
()def
readLine
([maxlen=0])def
realNumberNotation
()def
realNumberPrecision
()def
reset
()def
resetStatus
()def
seek
(pos)def
setAutoDetectUnicode
(enabled)def
setCodec
(codec)def
setCodec
(codecName)def
setDevice
(device)def
setFieldAlignment
(alignment)def
setFieldWidth
(width)def
setGenerateByteOrderMark
(generate)def
setIntegerBase
(base)def
setLocale
(locale)def
setNumberFlags
(flags)def
setPadChar
(ch)def
setRealNumberNotation
(notation)def
setRealNumberPrecision
(precision)def
setStatus
(status)def
skipWhiteSpace
()def
status
()def
string
()
Detailed Description¶
QTextStream
can operate on aQIODevice
, aQByteArray
or aQString
. UsingQTextStream
‘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 stringQTextStream
operates on by callingsetDevice()
orsetString()
. You can seek to a position by callingseek()
, andatEnd()
will return true when there is no data left to be read. If you callflush()
,QTextStream
will empty all data from its write buffer into the device and callflush()
on the device.Internally,
QTextStream
uses a Unicode based buffer, andQTextCodec
is used byQTextStream
to automatically support different character sets. By default,codecForLocale()
is used for reading and writing, but you can also set the codec by callingsetCodec()
. 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 callingsetGenerateByteOrderMark
(true). WhenQTextStream
operates on aQString
directly, the codec is disabled.There are three general ways to use
QTextStream
when reading text files:
Chunk by chunk, by calling
readLine()
orreadAll()
.Word by word.
QTextStream
supports streaming intoQString
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, callskipWhiteSpace()
.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 usingreadLine()
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 callingsetIntegerBase()
. Example: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 callingsetFieldWidth()
andsetPadChar()
. UsesetFieldAlignment()
to set the alignment within each field. For real numbers, callsetRealNumberNotation()
andsetRealNumberPrecision()
to set the notation (SmartNotation
,ScientificNotation
,FixedNotation
) and precision in digits of the generated number. Some extra number formatting options are also available throughsetNumberFlags()
.Like
<iostream>
in the standard C++ library,QTextStream
also defines several global manipulator functions:
Manipulator
Description
Same as
setIntegerBase
(2).Same as
setIntegerBase
(8).Same as
setIntegerBase
(10).Same as
setIntegerBase
(16).Same as
setNumberFlags
(numberFlags()
|ShowBase
).Same as
setNumberFlags
(numberFlags()
|ForceSign
).Same as
setNumberFlags
(numberFlags()
|ForcePoint
).Same as
setNumberFlags
(numberFlags()
& ~ShowBase
).Same as
setNumberFlags
(numberFlags()
& ~ForceSign
).Same as
setNumberFlags
(numberFlags()
& ~ForcePoint
).Same as
setNumberFlags
(numberFlags()
|UppercaseBase
).Same as
setNumberFlags
(numberFlags()
|UppercaseDigits
).Same as
setNumberFlags
(numberFlags()
& ~UppercaseBase
).Same as
setNumberFlags
(numberFlags()
& ~UppercaseDigits
).Same as
setRealNumberNotation
(FixedNotation
).Same as
setRealNumberNotation
(ScientificNotation
).Same as
setFieldAlignment
(AlignLeft
).Same as
setFieldAlignment
(AlignRight
).Same as
setFieldAlignment
(AlignCenter
).Same as operator<<(’\n’) and
flush()
.Same as
flush()
.Same as
reset()
.Same as
skipWhiteSpace()
.Same as
setGenerateByteOrderMark
(true).In addition, Qt provides three global manipulators that take a parameter:
qSetFieldWidth()
,qSetPadChar()
, andqSetRealNumberPrecision()
.See also
QDataStream
QIODevice
QFile
QBuffer
QTcpSocket
Text Codecs Example
- class PySide2.QtCore.QTextStream¶
PySide2.QtCore.QTextStream(array[, openMode=QIODevice.ReadWrite])
PySide2.QtCore.QTextStream(device)
- param openMode:
OpenMode
- param array:
- param device:
Constructs a
QTextStream
. Before you can use it for reading or writing, you must assign a device or a string.See also
setDevice()
setString()
Constructs a
QTextStream
that operates onarray
, usingopenMode
to define the open mode. Internally, the array is wrapped by aQBuffer
.Constructs a
QTextStream
that operates ondevice
.
- PySide2.QtCore.QTextStream.RealNumberNotation¶
This enum specifies which notations to use for expressing
float
anddouble
as strings.Constant
Description
QTextStream.ScientificNotation
Scientific notation (
printf()
’s%e
flag).QTextStream.FixedNotation
Fixed-point notation (
printf()
’s%f
flag).QTextStream.SmartNotation
Scientific or fixed-point notation, depending on which makes most sense (
printf()
’s%g
flag).See also
- PySide2.QtCore.QTextStream.FieldAlignment¶
This enum specifies how to align text in fields when the field is wider than the text that occupies it.
Constant
Description
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.
See also
- PySide2.QtCore.QTextStream.Status¶
This enum describes the current status of the text stream.
Constant
Description
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.
See also
- PySide2.QtCore.QTextStream.NumberFlag¶
This enum specifies various flags that can be set to affect the output of integers,
float
s, anddouble
s.Constant
Description
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.
See also
- PySide2.QtCore.QTextStream.atEnd()¶
- Return type:
bool
Returns
true
if there is no more data to be read from theQTextStream
; otherwise returnsfalse
. This is similar to, but not the same as callingatEnd()
, asQTextStream
also takes into account its internal Unicode buffer.
- PySide2.QtCore.QTextStream.autoDetectUnicode()¶
- Return type:
bool
Returns
true
if automatic Unicode detection is enabled, otherwise returnsfalse
. Automatic Unicode detection is enabled by default.
- PySide2.QtCore.QTextStream.codec()¶
- Return type:
Returns the codec that is current assigned to the stream.
See also
- PySide2.QtCore.QTextStream.device()¶
- Return type:
Returns the current device associated with the
QTextStream
, orNone
if no device has been assigned.See also
- PySide2.QtCore.QTextStream.fieldAlignment()¶
- Return type:
Returns the current field alignment.
See also
- PySide2.QtCore.QTextStream.fieldWidth()¶
- Return type:
int
Returns the current field width.
See also
- PySide2.QtCore.QTextStream.flush()¶
Flushes any buffered data waiting to be written to the device.
If
QTextStream
operates on a string, this function does nothing.
- PySide2.QtCore.QTextStream.generateByteOrderMark()¶
- Return type:
bool
Returns
true
ifQTextStream
is set to generate the UTF BOM (Byte Order Mark) when using a UTF codec; otherwise returnsfalse
. UTF BOM generation is set to false by default.See also
- PySide2.QtCore.QTextStream.integerBase()¶
- Return type:
int
Returns the current base of integers. 0 means that the base is detected when reading, or 10 (decimal) when generating numbers.
See also
setIntegerBase()
number()
numberFlags()
- PySide2.QtCore.QTextStream.locale()¶
- Return type:
Returns the locale for this stream. The default locale is C.
See also
- PySide2.QtCore.QTextStream.numberFlags()¶
- Return type:
NumberFlags
Returns the current number flags.
- PySide2.QtCore.QTextStream.__lshift__(s)¶
- Parameters:
s – str
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(i)
- Parameters:
i – int
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(i)
- Parameters:
i –
long
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(ch)
- Parameters:
ch –
QChar
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(m)
- Parameters:
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(ch)
- Parameters:
ch –
char
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(array)
- Parameters:
array –
PySide2.QtCore.QByteArray
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(arg__2)
- Parameters:
arg__2 –
PySide2.QtXml.QDomNode
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(arg__2)
- Parameters:
arg__2 –
PySide2.QtWidgets.QSplitter
- Return type:
Note
This function is deprecated.
- PySide2.QtCore.QTextStream.__lshift__(s)
- Parameters:
s –
QStringRef
- Return type:
- PySide2.QtCore.QTextStream.__lshift__(f)
- Parameters:
f –
double
- Return type:
- PySide2.QtCore.QTextStream.__rshift__(array)¶
- Parameters:
array –
PySide2.QtCore.QByteArray
- Return type:
- PySide2.QtCore.QTextStream.__rshift__(arg__2)
- Parameters:
arg__2 –
PySide2.QtWidgets.QSplitter
- Return type:
Note
This function is deprecated.
- PySide2.QtCore.QTextStream.padChar()¶
- Return type:
QChar
Returns the current pad character.
See also
- PySide2.QtCore.QTextStream.pos()¶
- Return type:
int
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).
Because
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.See also
- PySide2.QtCore.QTextStream.read(maxlen)¶
- Parameters:
maxlen – int
- Return type:
str
Reads at most
maxlen
characters from the stream, and returns the data read as aQString
.See also
- PySide2.QtCore.QTextStream.readAll()¶
- Return type:
str
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.Calling
readLine()
is better if you do not know how much data is available.See also
- PySide2.QtCore.QTextStream.readLine([maxlen=0])¶
- Parameters:
maxlen – int
- Return type:
str
Reads one line of text from the stream, and returns it as a
QString
. The maximum allowed line length is set tomaxlen
. If the stream contains lines longer than this, then the lines will be split aftermaxlen
characters and returned in parts.If
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 usingatEnd()
.See also
- PySide2.QtCore.QTextStream.realNumberNotation()¶
- Return type:
Returns the current real number notation.
- PySide2.QtCore.QTextStream.realNumberPrecision()¶
- Return type:
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.
See also
Status
status()
setStatus()
- PySide2.QtCore.QTextStream.seek(pos)¶
- Parameters:
pos – int
- Return type:
bool
Seeks to the position
pos
in the device. Returnstrue
on success; otherwise returnsfalse
.
- PySide2.QtCore.QTextStream.setAutoDetectUnicode(enabled)¶
- Parameters:
enabled – bool
If
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)¶
- Parameters:
codec –
PySide2.QtCore.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.If
QTextStream
operates on a string, this function does nothing.Warning
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.
See also
- PySide2.QtCore.QTextStream.setCodec(codecName)
- Parameters:
codecName – str
Sets the codec for this stream to the
QTextCodec
for the encoding specified bycodecName
. Common values forcodecName
include “ISO 8859-1”, “UTF-8”, and “UTF-16”. If the encoding isn’t recognized, nothing happens.Example:
out = QTextStream(file) out.setCodec("UTF-8")
See also
- PySide2.QtCore.QTextStream.setDevice(device)¶
- Parameters:
device –
PySide2.QtCore.QIODevice
Sets the current device to
device
. If a device has already been assigned,QTextStream
will callflush()
before the old device is replaced.Note
This function resets locale to the default locale (‘C’) and codec to the default codec,
codecForLocale()
.See also
device()
setString()
- PySide2.QtCore.QTextStream.setFieldAlignment(alignment)¶
- Parameters:
alignment –
FieldAlignment
Sets the field alignment to
mode
. When used together withsetFieldWidth()
, this function allows you to generate formatted output with text aligned to the left, to the right or center aligned.See also
- PySide2.QtCore.QTextStream.setFieldWidth(width)¶
- Parameters:
width – int
Sets the current field width to
width
. Ifwidth
is 0 (the default), the field width is equal to the length of the generated text.Note
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.
See also
- PySide2.QtCore.QTextStream.setGenerateByteOrderMark(generate)¶
- Parameters:
generate – bool
If
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. Ifgenerate
is false, no BOM will be inserted. This function must be called before any data is written. Otherwise, it does nothing.See also
- PySide2.QtCore.QTextStream.setIntegerBase(base)¶
- Parameters:
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). Ifbase
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.See also
integerBase()
number()
setNumberFlags()
- PySide2.QtCore.QTextStream.setLocale(locale)¶
- Parameters:
locale –
PySide2.QtCore.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.
See also
- PySide2.QtCore.QTextStream.setNumberFlags(flags)¶
- Parameters:
flags –
NumberFlags
Sets the current number flags to
flags
.flags
is a set of flags from theNumberFlag
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)¶
- Parameters:
ch –
QChar
Sets the pad character to
ch
. The default value is the ASCII space character (’ ‘), orQChar
(0x20). This character is used to fill in the space in fields when generating text.Example:
s = QString() out = QTextStream(s) out.setFieldWidth(10) out.setFieldAlignment(QTextStream::AlignCenter) out.setPadChar('-') out << "Qt" << "rocks!"
The string
s
contains:----Qt------rocks!--
See also
- PySide2.QtCore.QTextStream.setRealNumberNotation(notation)¶
- Parameters:
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)¶
- Parameters:
precision – int
Sets the precision of real numbers to
precision
. This value describes the number of fraction digitsQTextStream
should write when generating real numbers.The precision cannot be a negative value. The default value is 6.
- PySide2.QtCore.QTextStream.setStatus(status)¶
- Parameters:
status –
Status
Sets the status of the text stream to the
status
given.Subsequent calls to are ignored until
resetStatus()
is called.See also
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()
returnstrue
.See also
operator>>()
- PySide2.QtCore.QTextStream.status()¶
- Return type:
Returns the status of the text stream.
See also
Status
setStatus()
resetStatus()
- PySide2.QtCore.QTextStream.string()¶
- Return type:
str
Returns the current string assigned to the
QTextStream
, orNone
if no string has been assigned.See also
setString()
device()
© 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.