0

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
WangTao
  • 3
  • 3

2 Answers2

0

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();
Community
  • 1
  • 1
Son-Huy Pham
  • 1,899
  • 18
  • 19
0

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'
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • accepted answer proofs that you should write that `str` is python string. Anyway this answer is a bit to complicated, [see this page](http://www.commandprompt.com/community/pyqt/x2068). So to fix you code this should be enough: `streamin = QTextStream(QString(str))` – Marek R Dec 09 '13 at 09:37
  • 1
    @MarekR. You missed that the OP is using PyQt5. There is no QString in PyQt5, so only a QIODevice or QByteArray can be passed to the QTextStream constructor. Of course, your suggestion would work with PyQt4. Personally, I would avoid all the complications and use python's [io](http://docs.python.org/3/library/io.html#) module for this kind of thing. – ekhumoro Dec 09 '13 at 18:04