私はPyQt5でテキストエディタを開発しています。私は "Find next ..."機能を実装しています。ユーザーは、検索したい文字列を入力します。 「次を検索」ボタンをクリックするたびに、次の一致する文字列が強調表示されます。 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)
一致する文字列が(ビューポートのうちの)ページの下部にある場合に問題があり、Iテキストエリアを自動的に下に(または上に)スクロールします。 QTextEditのensureCursorVisible()メソッドを試しましたが、動作しません。
brute-forceの解決策は、scrollbar.setValue()メソッドを使用してその行にスクロールするよりも、現在の行のy座標をピクセル単位で計算することです。
確かに 'ensureCursorVisible()'が機能するために 'textarea.setTextCursor(cursor)'を呼び出さなければなりません。 – ekhumoro
これはうまくいきました... QTextEdit.textCursor()メソッドから返されるカーソルは、テキストエリアのカーソルとして「設定」されている必要があります。大いに感謝する。 – NewBieBR