Why does select(QTextCursor::BlockUnderCursor) include an extra junk character?
Windows 7 SP1
MSVS 2010
Qt 4.8.4
I am using QTextCursor to grab each block's text. I use select(QTextCursor::BlockUnderCursor) to grab the text and then go to the next block with movePosition(QTextCursor::NextBlock). But when I again select(QTextCursor::BlockUnderCursor) I get an extra junk character in the QString and the anchor has moved to the end of the previous block.
Using this for text.txt:
This code's comments walks through the issue and asks the questions:
Code:
#include <QTGui>
int main(int argc, char *argv[])
{
editor->setDocument(document);
editor->setPlainText(file.readAll());
int pos = cursor->position(); // = 0
int anchor = cursor->anchor(); // = 0
pos = cursor->position(); // = 1
anchor = cursor->anchor(); // = 0
QString text
= cursor
->selectedText
();
// = "A" int size = text.size(); // = 1
pos = cursor->position(); // = 2
anchor = cursor->anchor(); // = 2
pos = cursor->position(); // = 3
anchor = cursor->anchor(); // = 1 Why not 2?
text = cursor->selectedText(); // "B" in debugger
// but text.at(0) = junk & test.at(1) = "B"
size = text.size(); // = 2 Why? Why not 1?
return app.exec();
}
Re: Why does select(QTextCursor::BlockUnderCursor) include an extra junk character?
From the docs ( QTextCursor::selectedText() ):
Quote:
Note: If the selection obtained from an editor spans a line break, the text will contain a Unicode U+2029 paragraph separator character instead of a newline \n character.
You can check by putting the following statement in your code:
Code:
qDebug
() <<
QString("U+%1").
arg(text.
at(0).
unicode(),
0,
16);
Re: Why does select(QTextCursor::BlockUnderCursor) include an extra junk character?
Thanks for the education! Now I get it. In other words, selecting the block includes the starting paragraph separator. The first block doesn't have a starting SEP. Therefore, need to exclude the first character if one wants to extract the text alone of subsequent blocks.
Re: Why does select(QTextCursor::BlockUnderCursor) include an extra junk character?
You're welcome. If you just want the text use QString::trimmed():
Code:
text = cursor->selectedText().trimmed();