mspehar
mspehar

Reputation: 587

QPlainTextEdit / QTextCursor - how to get lines above and below cursor until above and below are empty lines

Is there a way to extract several rows of text relative to the cursor in QPlainTextEdit, but only the lines above and below cursor until empty line is found?

Example data:

AA
BB
CC

DD
EE
FF

GG
HH
II

Based on the QTextCursor documentation, when i want to extract a block i get a paragraph which is defined as a text which ends with a new line. I can loop until i find an empty line, but this seems a bad solution.

Upvotes: 1

Views: 724

Answers (1)

eyllanesc
eyllanesc

Reputation: 244003

The solution is to iterate through the QTextBlock as shown below:

#include <QApplication>
#include <QPlainTextEdit>
#include <QTextBlock>

#include <QDebug>

static QString getLinesBetweenSpaces(const QTextBlock & block){
   QTextBlock before = block;
   QTextBlock after = block;

   if(block.text().trimmed().isEmpty())
       return "";

   QStringList lines{block.text()};

   do{
       before = before.previous();
       if(before.text().trimmed().isEmpty())
           break;
       lines.prepend(before.text());
   }
   while(before.isValid());

   do{
       after = after.next();
       if(after.text().trimmed().isEmpty())
           break;
        lines.append(after.text());
   }
   while(after.isValid());
   return lines.join("\n");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    const QStringList lines = {"AA", "BB", "CC", " ", "DD", "EE", "FF", " ", "GG", "HH", "II"};
    const QString text = lines.join("\n");
    QPlainTextEdit w;
    w.setPlainText(text);

    QObject::connect(&w, &QPlainTextEdit::cursorPositionChanged, [&w](){
       qDebug()<<  getLinesBetweenSpaces(w.textCursor().block());
    });
    w.show();

    return a.exec();
}

Upvotes: 2

Related Questions