Home · All Classes · Modules

QTextStream Class Reference
[QtCore module]

The QTextStream class provides a convenient interface for reading and writing text. More...

Types

Methods

Special Methods


Detailed Description

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

QTextStream can operate on a QIODevice, a QByteArray or a 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:

 QFile data("output.txt");
 if (data.open(QFile.WriteOnly | QFile.Truncate)) {
     QTextStream out(&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:

 QTextStream stream(stdin);
 QString line;
 do {
     line = stream.readLine();
 } while (!line.isNull());

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

Internally, QTextStream uses a Unicode based buffer, and QTextCodec is used by QTextStream to automatically support different character sets. By default, QTextCodec.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:

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 QFile.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(). Example:

 QTextStream in("0x50 0x20");
 int firstNumber, secondNumber;

 in >> firstNumber;             // firstNumber == 80
 in >> dec >> secondNumber;     // secondNumber == 0

 char ch;
 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(). Use 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().

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

Manipulator Description
bin Same as setIntegerBase(2).
oct Same as setIntegerBase(8).
dec Same as setIntegerBase(10).
hex Same as setIntegerBase(16).
showbase Same as setNumberFlags(numberFlags() | ShowBase).
forcesign Same as setNumberFlags(numberFlags() | ForceSign).
forcepoint Same as setNumberFlags(numberFlags() | ForcePoint).
noshowbase Same as setNumberFlags(numberFlags() & ~ShowBase).
noforcesign Same as setNumberFlags(numberFlags() & ~ForceSign).
noforcepoint Same as setNumberFlags(numberFlags() & ~ForcePoint).
uppercasebase Same as setNumberFlags(numberFlags() | UppercaseBase).
uppercasedigits Same as setNumberFlags(numberFlags() | UppercaseDigits).
lowercasebase Same as setNumberFlags(numberFlags() & ~UppercaseBase).
lowercasedigits Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
fixed Same as setRealNumberNotation(FixedNotation).
scientific Same as setRealNumberNotation(ScientificNotation).
left Same as setFieldAlignment(AlignLeft).
right Same as setFieldAlignment(AlignRight).
center Same as setFieldAlignment(AlignCenter).
endl Same as operator<<('\n') and flush().
flush Same as flush().
reset Same as reset().
ws Same as skipWhiteSpace().
bom Same as setGenerateByteOrderMark(true).

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


Type Documentation

QTextStream.FieldAlignment

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

Constant Value Description
QTextStream.AlignLeft 0 Pad on the right side of fields.
QTextStream.AlignRight 1 Pad on the left side of fields.
QTextStream.AlignCenter 2 Pad on both sides of field.
QTextStream.AlignAccountingStyle 3 Same as AlignRight, except that the sign of a number is flush left.

See also setFieldAlignment().

QTextStream.NumberFlag

This enum specifies various flags that can be set to affect the output of integers, floats, and doubles.

Constant Value Description
QTextStream.ShowBase 0x1 Show the base as a prefix if the base is 16 ("0x"), 8 ("0"), or 2 ("0b").
QTextStream.ForcePoint 0x2 Always put the decimal separator in numbers, even if there are no decimals.
QTextStream.ForceSign 0x4 Always put the sign in numbers, even for positive numbers.
QTextStream.UppercaseBase 0x8 Use uppercase versions of base prefixes ("0X", "0B").
QTextStream.UppercaseDigits 0x10 Use uppercase letters for expressing digits 10 to 35 instead of lowercase.

The NumberFlags type is a typedef for QFlags<NumberFlag>. It stores an OR combination of NumberFlag values.

See also setNumberFlags().

QTextStream.RealNumberNotation

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

Constant Value Description
QTextStream.ScientificNotation 2 Scientific notation (printf()'s %e flag).
QTextStream.FixedNotation 1 Fixed-point notation (printf()'s %f flag).
QTextStream.SmartNotation 0 Scientific or fixed-point notation, depending on which makes most sense (printf()'s %g flag).

See also setRealNumberNotation().

QTextStream.Status

This enum describes the current status of the text stream.

Constant Value Description
QTextStream.Ok 0 The text stream is operating normally.
QTextStream.ReadPastEnd 1 The text stream has read past the end of the data in the underlying device.
QTextStream.ReadCorruptData 2 The text stream has read corrupt data.
QTextStream.WriteFailed 3 The text stream cannot write to the underlying device.

See also status().


Method Documentation

QTextStream.__init__ (self)

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

See also setDevice() and setString().

QTextStream.__init__ (self, QIODevice device)

Constructs a QTextStream that operates on device.

QTextStream.__init__ (self, QString string, QIODevice.OpenMode mode = QIODevice.ReadWrite)

Constructs a QTextStream that operates on fileHandle, using openMode to define the open mode. Internally, a QFile is created to handle the FILE pointer.

This constructor is useful for working directly with the common FILE based input and output streams: stdin, stdout and stderr. Example:

 QString str;
 QTextStream in(stdin);
 in >> str;

QTextStream.__init__ (self, QByteArray array, QIODevice.OpenMode mode = QIODevice.ReadWrite)

Constructs a QTextStream that operates on string, using openMode to define the open mode.

bool QTextStream.atEnd (self)

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

bool QTextStream.autoDetectUnicode (self)

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

See also setAutoDetectUnicode() and setCodec().

QTextCodec QTextStream.codec (self)

Returns the codec that is current assigned to the stream.

See also setCodec(), setAutoDetectUnicode(), and locale().

QIODevice QTextStream.device (self)

Returns the current device associated with the QTextStream, or 0 if no device has been assigned.

See also setDevice() and string().

FieldAlignment QTextStream.fieldAlignment (self)

Returns the current field alignment.

See also setFieldAlignment() and fieldWidth().

int QTextStream.fieldWidth (self)

Returns the current field width.

See also setFieldWidth().

QTextStream.flush (self)

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

If QTextStream operates on a string, this function does nothing.

bool QTextStream.generateByteOrderMark (self)

Returns 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.

See also setGenerateByteOrderMark().

int QTextStream.integerBase (self)

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

See also setIntegerBase(), QString.number(), and numberFlags().

QLocale QTextStream.locale (self)

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

This function was introduced in Qt 4.5.

See also setLocale().

NumberFlags QTextStream.numberFlags (self)

Returns the current number flags.

See also setNumberFlags(), integerBase(), and realNumberNotation().

QChar QTextStream.padChar (self)

Returns the current pad character.

See also setPadChar() and setFieldWidth().

int QTextStream.pos (self)

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.

This function was introduced in Qt 4.2.

See also seek().

QString QTextStream.read (self, int maxlen)

Reads at most maxlen characters from the stream, and returns the data read as a QString.

This function was introduced in Qt 4.1.

See also readAll(), readLine(), and QIODevice.read().

QString QTextStream.readAll (self)

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 readLine().

QString QTextStream.readLine (self, int maxLength = 0)

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.

If maxlen is 0, the lines can be of any length. A common value for maxlen is 75.

The returned line has no trailing end-of-line characters ("\n" or "\r\n"), so calling QString.trimmed() is unnecessary.

If the stream has read to the end of the file, readLine() 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().

See also readAll() and QIODevice.readLine().

RealNumberNotation QTextStream.realNumberNotation (self)

Returns the current real number notation.

See also setRealNumberNotation(), realNumberPrecision(), numberFlags(), and integerBase().

int QTextStream.realNumberPrecision (self)

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

See also setRealNumberPrecision(), setRealNumberNotation(), realNumberNotation(), numberFlags(), and integerBase().

QTextStream.reset (self)

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

QTextStream.resetStatus (self)

Resets the status of the text stream.

This function was introduced in Qt 4.1.

See also QTextStream.Status, status(), and setStatus().

bool QTextStream.seek (self, int pos)

Seeks to the position pos in the device. Returns true on success; otherwise returns false.

QTextStream.setAutoDetectUnicode (self, bool enabled)

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-16 or UTF-32 BOM (Byte Order Mark). 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.

See also autoDetectUnicode() and setCodec().

QTextStream.setCodec (self, QTextCodec codec)

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, QTextCodec.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 codec(), setAutoDetectUnicode(), and setLocale().

QTextStream.setCodec (self, str codecName)

Sets the codec for this stream to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.

Example:

 QTextStream out(&file);
 out.setCodec("UTF-8");

See also QTextCodec.codecForName() and setLocale().

QTextStream.setDevice (self, QIODevice device)

Sets the current device to device. If a device has already been assigned, QTextStream will call flush() before the old device is replaced.

Note: This function resets locale to the default locale ('C') and codec to the default codec, QTextCodec.codecForLocale().

See also device() and setString().

QTextStream.setFieldAlignment (self, FieldAlignment alignment)

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.

See also fieldAlignment() and setFieldWidth().

QTextStream.setFieldWidth (self, int width)

Sets the current field width to width. If width 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 fieldWidth() and setPadChar().

QTextStream.setGenerateByteOrderMark (self, bool generate)

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. If generate is false, no BOM will be inserted. This function must be called before any data is written. Otherwise, it does nothing.

See also generateByteOrderMark() and bom().

QTextStream.setIntegerBase (self, int base)

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.

See also integerBase(), QString.number(), and setNumberFlags().

QTextStream.setLocale (self, QLocale locale)

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.

This function was introduced in Qt 4.5.

See also locale().

QTextStream.setNumberFlags (self, NumberFlags flags)

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).

See also numberFlags(), setIntegerBase(), and setRealNumberNotation().

QTextStream.setPadChar (self, QChar ch)

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.

Example:

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

The string s contains:

 ----Qt------rocks!--

See also padChar() and setFieldWidth().

QTextStream.setRealNumberNotation (self, RealNumberNotation notation)

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.

See also realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), and setIntegerBase().

QTextStream.setRealNumberPrecision (self, int precision)

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.

See also realNumberPrecision() and setRealNumberNotation().

QTextStream.setStatus (self, Status status)

Sets the status of the text stream to the status given.

Subsequent calls to setStatus() are ignored until resetStatus() is called.

This function was introduced in Qt 4.1.

See also Status, status(), and resetStatus().

QTextStream.setString (self, QString string, QIODevice.OpenMode mode = QIODevice.ReadWrite)

Sets the current string to string, using the given openMode. If a device has already been assigned, QTextStream will call flush() before replacing it.

See also string() and setDevice().

QTextStream.skipWhiteSpace (self)

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 QChar.isSpace() returns true.

See also operator>>().

Status QTextStream.status (self)

Returns the status of the text stream.

See also QTextStream.Status, setStatus(), and resetStatus().

QString QTextStream.string (self)

Returns the current string assigned to the QTextStream, or 0 if no string has been assigned.

See also setString() and device().

QTextStream __lshift__ (self, QDomNode)

This method is only available if the QtXml module is imported.

QTextStream __lshift__ (self, QSplitter)

This method is only available if the QtGui module is imported.

QTextStream __rshift__ (self, QSplitter)

This method is only available if the QtGui module is imported.

QTextStream QTextStream.__lshift__ (self, float f)

QTextStream QTextStream.__lshift__ (self, bool b)

QTextStream QTextStream.__lshift__ (self, int i)

QTextStream QTextStream.__lshift__ (self, int i)

QTextStream QTextStream.__lshift__ (self, int i)

QTextStream QTextStream.__lshift__ (self, QString s)

QTextStream QTextStream.__lshift__ (self, QByteArray array)

QTextStream QTextStream.__lshift__ (self, QTextStreamManipulator m)

QTextStream QTextStream.__rshift__ (self, QChar ch)

QTextStream QTextStream.__rshift__ (self, QString s)

QTextStream QTextStream.__rshift__ (self, QByteArray array)


PyQt 4.9.4 for WindowsCopyright © Riverbank Computing Ltd and Nokia 2012Qt 4.8.2