【发布时间】:2017-09-04 15:31:10
【问题描述】:
我正在使用 PyQt5 开发一个文本编辑器,并且我正在实现“查找下一个...”功能。用户输入他想要搜索的字符串。每次他单击“查找下一个”按钮时,下一个匹配的字符串都会突出显示。
我已经像这样使用 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.setTextCursor(cursor)才能让ensureCursorVisible()工作。 -
它工作了 omg... 我非常确定 QTextEdit.textCursor() 方法返回的光标必须“设置”为文本区域的光标。非常感谢。