QTextEdit 按行遍历时在当前行高亮
时间: 2024-06-13 13:09:40 浏览: 187
可以通过以下方法实现QTextEdit按行遍历时在当前行高亮:
```python
# 获取QTextEdit的光标
cursor = textEdit.textCursor()
# 获取当前行号
line_num = cursor.blockNumber()
# 获取当前行的文本
line_text = cursor.block().text()
# 获取当前行的开始位置和结束位置
start_pos = cursor.block().position()
end_pos = start_pos + len(line_text)
# 设置当前行的高亮
highlight = QTextEdit.ExtraSelection()
highlight.format.setBackground(QColor(Qt.yellow))
highlight.format.setProperty(QTextFormat.FullWidthSelection, True)
highlight.cursor = cursor
highlight.cursor.setPosition(start_pos, QTextCursor.MoveAnchor)
highlight.cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
# 将高亮设置到QTextEdit中
extra_selections = []
extra_selections.append(highlight)
textEdit.setExtraSelections(extra_selections)
```
阅读全文