Remove a line/block from QTextEdit

Andrejs Cainikovs picture Andrejs Cainikovs · May 2, 2012 · Viewed 7.7k times · Source

I'm struggling with block/line removal from QTextEdit. Code below should(?) work but it ends up in infinite loop for some unknown to me reason. I have a suspicion that next() and previous() are not welcome if QTextDocument is being edited.

QTextBlock block = document()->begin();
while (block.isValid()) {
    if (to_do_or_not_to_do(block)) {
        QTextCursor cursor(block);
        cursor.select(QTextCursor::BlockUnderCursor);
        cursor.removeSelectedText();
    }
    block = block.next();
}

Iterating using QTextDocument::findBlockByNumber() and deleting block in the same way as above didn't worked either.

I would appreciate if someone could point me into right direction on how to iterate trough all the blocks and remove them if needed.

P.S.
In my particular case one block = one line.
Qt 4.6.2, Ubuntu 10.04 x64

Answer

gumik picture gumik · May 2, 2012

Changing it a little works for me:

while (block.isValid()) {
    if (to_do_or_not_to_do(block)) {
        QTextCursor cursor(block);
        block = block.next();
        cursor.select(QTextCursor::BlockUnderCursor);
        cursor.removeSelectedText();
    }
    else
        block = block.next();
}