QTextCursor 和 beginEditBlock [英] QTextCursor and beginEditBlock
问题描述
我在 QPlainTextEdit 中有一些文本,其中每行以 10 个空格开头:
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
当我删除 beginEditBlock()
和 endEditBlock()
时,一切正常.
When I remove beginEditBlock()
and endEditBlock()
everything works fine.
请问,有人知道为什么会这样吗?
Please, does anyone know why is this happening?
推荐答案
在这种情况下 block != endBlock
你的光标永远不会到达最后一个块.你应该使用这个:
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();
}
这篇关于QTextCursor 和 beginEditBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!