How can I highlight a full row of text in a QPlainTextEdit widget?

Question:

I’ve made a little editor using a QPlainTextEdit and I’d like to be able to highlight a whole row of text to show which line has an error on.

I can format the text, but I can’t work out how to set the cursor position to the start and end position of the text on a specified row.

This snippet shows where I’ve gotten to:

editor = QtGui.QPlainTextEdit()

fmt = QtGui.QTextCharFormat()
fmt.setUnderlineColor(Qt.red)
fmt.setUnderlineStyle(QtGui.QTextCharFormat.SpellCheckUnderline)

# I'd like these values to encompass the whole of say, line 4 of the text
begin = 0 
end = 5

cursor = QtGui.QTextCursor(editor.document())
cursor.setPosition(begin, QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
cursor.setCharFormat(fmt)

Can I work out the beginning and end points for the cursor to highlight, from just a row number?

Asked By: Nodgers

||

Answers:

Thanks to Ekrumoro I managed to get this working like so:

editor = QtGui.QPlainTextEdit()

fmt = QtGui.QTextCharFormat()
fmt.setUnderlineColor(Qt.red)
fmt.setUnderlineStyle(QtGui.QTextCharFormat.SpellCheckUnderline)

block = editor.document().findBlockByLineNumber(line)
blockPos = block.position()

cursor = QtGui.QTextCursor(editor.document())
cursor.setPosition(blockPos)
cursor.select(QtGui.QTextCursor.LineUnderCursor)
cursor.setCharFormat(fmt)
Answered By: Nodgers
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.