How to read a specific line from QPlainTextEdit

I have a QPlainTextEdit with this content:

This is a QPlainTextEdit 

I am looking in the Qt documentation for a read command, for example. fourth line (QPlainTextEdit): such as readLine (int line), but I could not find anything.

+6
source share
2 answers

I would do the following:

 QPlainTextEdit edit; edit.setPlainText("This\nis\na\nQPlainTextEdit"); QTextDocument *doc = edit.document(); QTextBlock tb = doc->findBlockByLineNumber(1); // The second line. QString s = tb.text(); // returns 'is' 
+6
source

You need to get plain text and split it line by line. For instance:

 QStringList lines = plainTextEdit->plainText() .split('\n', QString::SkipEmptyParts); if (lines.count() > 3) qDebug() << "fourth line:" << lines.at(3); 

If you want to include blank lines, remove the SkipEmptyParts argument - the default is KeepEmptyParts .

You can also use a text stream:

 QString text = plainTextEdit->plainText(); QTextStream str(&text, QIODevice::ReadOnly); QString line; for (int n = 0; !str.atEnd() && n < 3; ++n) line = str.readLine(); qDebug() << "fourth or last line:" << line; 
+1
source

All Articles