Use QTextStream to read the first line in a string

1.7k views Asked by At

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.

2

There are 2 answers

2
ekhumoro On BEST ANSWER

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'
1
Son-Huy Pham On

I'm basically going to post a snippet of code from the Qt Documentation Site.

Better yet... here's something from stackoverflow as well.

// Instead of feeding in stdin, you can feed in QFile - i.e. QIODevice
QFile file("myfile");
// ... open file etc etc
QTextStream stream(&file);
QString line;
line = stream.readLine();