user3204810
user3204810

Reputation: 391

How to read a specific line from QPlainTextEdit

I have a QPlainTextEdit with this content:

This
is
a
QPlainTextEdit

I'm searching in the Qt documentation for a comand to read, e.g. the fourth line (QPlainTextEdit): such like readLine(int line), but I could not find anything.

Upvotes: 9

Views: 8056

Answers (2)

vahancho
vahancho

Reputation: 21220

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'

Upvotes: 11

You need to get the plain text, and split it by lines. For example:

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

If you wish to include empty lines, then remove the SkipEmptyParts argument - it will default to KeepEmptyParts.

You can also use the 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;

Upvotes: 1

Related Questions