[英]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.