如何突出显示QPlainTextEdit小部件中的全部文本行?

问题描述:

我已经做了一个使用QPlainTextEdit的小编辑器,我希望能够突出显示一行文本以显示哪一行有错误。如何突出显示QPlainTextEdit小部件中的全部文本行?

我可以格式化文本,但我无法确定如何将光标位置设置为指定行上文本的开始和结束位置。

这个片断显示,我已经得到了:

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) 

我能为光标彰显制定出起点和终点,只从一个行号?

+3

试着这么做:'块= editor.document()findBlockByLineNumber(线); cursor.setPosition(block.position()); cursor.select(QTextCursor.LineUnderCursor)'。 – ekhumoro

+0

谢谢,这是工作! – Nodgers

感谢Ekrumoro我设法得到这个工作,像这样:

editor= QtGui.QTextCharFormat() 

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)