问题
I have some text in QPlainTextEdit, where every line starts with 10 spaces:
line1
line2
line3
line4
Then, I select few lines and in a loop I want to remove first two spaces from all the selected lines:
cursor.beginEditBlock();
for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
cursor.setPosition(block.position());
cursor.setPosition(block.position() + 2, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
}
cursor.endEditBlock();
The problem is that the code above "damages" the last selected line - as if it removed some kind of end-of-line marker - when I want to jump to the end of last line the cursor moves to the line below it, between first and second character. Even the selection does not show up properly after the edit - all the lines but the last one have selection indicator expanded to the right window edge and the last line has the indicator only as wide as the line.
line1 < 1. selected lines, run the code
line2 <
line3 < < 2. here I jump to end of line
| line4
^ 3. cursor appears here
When I remove beginEditBlock()
and endEditBlock()
everything works fine.
Please, does anyone know why is this happening?
回答1:
With this condition block != endBlock
your cursor will never reach the last block.
You should use this:
QTextBlock block = document->firstBlock();
while (block.isValid())
{
// do your stuff
block = block.next();
}
来源:https://stackoverflow.com/questions/15190437/qtextcursor-and-begineditblock