繁体   English   中英

PyQt5-滚动到QTextEdit的光标

[英]PyQt5 - Scroll to QTextEdit's cursor

我正在使用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) 

问题是,如果匹配的字符串位于页面底部(视口之外),我希望textarea自动向下(或向上滚动)。 我尝试使用QTextEdit的sureCursorVisible()方法,但是它不起作用。

蛮力解决方案是,使用scrollbar.setValue()方法滚动到该行,以像素为单位计算当前行的y坐标。

实际上,我只需要:

textarea.ensureCursorVisible()
#AND
textare.setTextCursor(cursor)

QTextEdit的textCursor()方法返回其光标的COPY,而不是实际的,因此我们必须使用setTextCursor()方法进行设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM