Question

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.

Was it helpful?

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'

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top