PyQt5 - 滚动到 QTextEdit 的光标
PyQt5 - Scroll to QTextEdit's cursor
我正在使用 PyQt5 开发一个文本编辑器,并且正在实现 "Find next..." 功能。用户输入他要搜索的字符串。每次他点击 "Find next" 按钮时,下一个匹配的字符串就会高亮显示。
我已经使用 QTextEdit.textCursor() 像这样完成了:
...
textarea = QTextEdit()
cursor = textarea.textCursor()
#This function returns an array: [start index of the matched string, end index of the matched string]
matched_string_indexes = findText(text_to_find, text,...)
#So now I can use setPosition to select the matched string
cursor.setPosition(array[0], QTextEdit.MoveAnchor)
cursor.setPosition(array[1], QTextEdit.KeepAnchor)
#Now that the matched string is seleted I can highlight it
highlightText(cursor)
问题是如果匹配字符串位于页面底部(在视口之外),我希望文本区域自动向下(或向上)滚动。我尝试使用 QTextEdit 的 ensureCursorVisible() 方法,但它不起作用。
一种强力解决方案是计算当前行的 y 坐标(以像素为单位),而不是使用 scrollbar.setValue() 方法滚动到该行。
其实我只需要:
textarea.ensureCursorVisible()
#AND
textare.setTextCursor(cursor)
QTextEdit 的 textCursor() 方法 returns 其光标的副本,而不是真正的光标,因此我们必须使用 setTextCursor() 方法对其进行设置。
我正在使用 PyQt5 开发一个文本编辑器,并且正在实现 "Find next..." 功能。用户输入他要搜索的字符串。每次他点击 "Find next" 按钮时,下一个匹配的字符串就会高亮显示。
我已经使用 QTextEdit.textCursor() 像这样完成了:
...
textarea = QTextEdit()
cursor = textarea.textCursor()
#This function returns an array: [start index of the matched string, end index of the matched string]
matched_string_indexes = findText(text_to_find, text,...)
#So now I can use setPosition to select the matched string
cursor.setPosition(array[0], QTextEdit.MoveAnchor)
cursor.setPosition(array[1], QTextEdit.KeepAnchor)
#Now that the matched string is seleted I can highlight it
highlightText(cursor)
问题是如果匹配字符串位于页面底部(在视口之外),我希望文本区域自动向下(或向上)滚动。我尝试使用 QTextEdit 的 ensureCursorVisible() 方法,但它不起作用。
一种强力解决方案是计算当前行的 y 坐标(以像素为单位),而不是使用 scrollbar.setValue() 方法滚动到该行。
其实我只需要:
textarea.ensureCursorVisible()
#AND
textare.setTextCursor(cursor)
QTextEdit 的 textCursor() 方法 returns 其光标的副本,而不是真正的光标,因此我们必须使用 setTextCursor() 方法对其进行设置。