How to to center selected text in QTextBrowser

563 Views Asked by At

The code posted below creates QTextBrowser window filling it with 100 lines of text: starting from MESSAGE-0000 all the way to MESSAGE-0099

enter image description here

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication([])

textBrowser = QtGui.QTextBrowser()
for i in range(100):
    textBrowser.insertPlainText('MESSAGE-%04d'%i + '\n')

textBrowser.show()
app.exec_()

Question: How to find a line number where its text says: MESSAGE-0051, then select or highlight it and then scroll to it so the selected-highlightet line is positioned at the top edge of the QTextBrowser window, so the result would look like this:

enter image description here

How to achieve it?

1

There are 1 best solutions below

0
On BEST ANSWER

If you search backwards, it will automatically scroll the selected line to the top of the viewport:

textBrowser.moveCursor(QtGui.QTextCursor.End)
textBrowser.find('MESSAGE-0051', QtGui.QTextDocument.FindBackward)

(Of course, if you search for say, MESSAGE-0095, it won't put the selected line at the top, because the view cannot scroll down that far).