Question

I need to remove some paragraphs from QTextDocument. I have tried code from this topic: Remove a line/block from QTextEdit, but QTextDocument.drawContents outputs empty line in place of removed block.

# create sample document
doc = QTextDocument()
cursor = QTextCursor(doc)
cursor.movePosition(QTextCursor.End)
cursor.insertText("First line\nSecond line\nThird line")

# now remove first line
cursor = QTextCursor(doc.findBlockByLineNumber(0))
cursor.select(QTextCursor.BlockUnderCursor)
cursor.removeSelectedText()

So, how to completely remove block?

Was it helpful?

Solution 2

I think this is a bug because it happens only for the first block. Other blocks are deleted completely without any problems. I found a workaround:

cursor = QTextCursor(doc.findBlockByLineNumber(0))
cursor.select(QTextCursor.BlockUnderCursor)
cursor.deleteChar()
cursor.deleteChar()

You should do it if you want to delete the first block. If you want to delete other blocks, use your original code.

Maybe it's appropriate to create new QTextDocument and copy all blocks except the block you want to delete.

OTHER TIPS

I know this thread is old, but I encountered this same issue recently. Calling deleteChar twice in a row (even if I only do it for the first block) caused some other squirrely behavior for me.

I found that calling removeSelectedText followed by deletaChar for every block worked perfectly for what I was doing. No idea why, but I hope this helps someone in the future.

cursor = QTextCursor(doc.firstBlock())
cursor.select(QTextCursor.BlockUnderCursor)
cursor.removeSelectedText()
cursor.deleteChar()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top