Search code examples
pythonqtqt4pyqtqtextdocument

Remove block from QTextDocument


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?


Solution

  • 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.