Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a specific line from QPlainTextEdit

Tags:

c++

qt

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.

like image 872
user3204810 Avatar asked Feb 07 '14 16:02

user3204810


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'
like image 94
vahancho Avatar answered Oct 01 '22 07:10

vahancho


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;
like image 43
Kuba hasn't forgotten Monica Avatar answered Oct 01 '22 08:10

Kuba hasn't forgotten Monica