Search code examples
pythonqtextbrowser

How to control QTextBrowser horizontal scroll bar


The code below create a single QTextBrowser widget filling it with the long lines of text. Since there was view.setLineWrapMode(0) applied the view does not wrap the text but places each line on a single line regardless of how long the line is. Notice that when the window is shown the horizontal scroll-bar is rewided all the way to the right: so we are seeing the end of the lines:

enter image description here

Instead I would like the textBrowser to set the horizontal scroll bar to the left so we could see the begining of the text line. Please see this image:

enter image description here

How to achieve this?

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

view = QtGui.QTextBrowser() 
for i in range(25):
    view.append(10*('Long Line of text # %004d '%i) )
view.setLineWrapMode(0)

view.show()
app.exec_()

Solution

  • You can get the Horizontal Scrollbar with {your QTextBrowser}.horizontalScrollBar(), then you have to place it in the initial position, that is, {your Scrollbar}.setValue(0):

    {your QTextBrowser}.horizontalScrollBar().setValue(0)
    

    Complete Code:

    import sys
    
    from PyQt4 import QtGui
    
    if __name__ == '__main__':
    
        app = QtGui.QApplication(sys.argv)
    
        view = QtGui.QTextBrowser()
        for i in range(25):
            view.append(10*('Long Line of text # %004d '%i) )
    
        view.setLineWrapMode(QtGui.QTextBrowser.NoWrap)
        view.show()
        view.horizontalScrollBar().setValue(0)
        sys.exit(app.exec_())
    

    Output:

    enter image description here