有没有一种方法可以提取相对于QPlainTextEdit中的光标的几行文本,但是只能找到光标上方和下方的行,直到找到空行?
示例数据:
AA
BB
CC
DD
EE
FF
GG
HH
II
基于QTextCursor文档,当我想提取一个块时,我得到了一个段落,该段落定义为以新行结尾的文本。我可以循环直到找到空行,但这似乎是一个不好的解决方案。
答案 0 :(得分:1)
解决方案是遍历QTextBlock
,如下所示:
#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();
}