1
我與深化發展一個PyQt5文本編輯器,我執行「查找下一個...」功能。用戶輸入他想要搜索的字符串。每次他點擊「查找下一個」按鈕時,下一個匹配的字符串將被突出顯示。 PyQt5 - 滾動到QTextEdit的自動光標
我已經做了,使用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的ensureCursorVisible()方法,但它不起作用。
蠻力的解決方案是計算當前行的Y coordiate在像素不是使用scrollbar.setValue()方法來滾動到該行。
當然,你將不得不調用'textarea.setTextCursor(光標)'爲了'ensureCursorVisible()'工作。 – ekhumoro
它的工作OMG ......我是很肯定的由QTextEdit.textCursor返回光標()方法必須是「套」爲文本區域的光標。萬分感謝。 – NewBieBR