Search code examples
pythonqtreadlinepyqt5qtextstream

Use QTextStream to read the first line in a string


How can I use QTextStream to read the first line in a string (read from a file before)?

streamin = QTextStream(str)
line = streamin.readLine()

It seems that this code doesn't work.


Solution

  • The QTextStream class does not accept python strings directly. For PyQt5, you must convert the string to a QByteArray first:

    >>> s = """\
    ... First Line
    ... Second Line
    ... Third Line
    ... """
    >>> ba = QtCore.QByteArray(s.encode('utf-8'))
    >>> ts = QtCore.QTextStream(ba)
    >>> ts.setCodec('utf-8')
    >>> ts.readLine()
    'First Line'