PyQt4: running QTextEdit on the nth line

I have a popup containing only QTextEdit, it has a lot of text, a lot of lines. I want it to highlight a specific line in a QTextEdit in show (). So the line I want is at the top.

Code snippet:

editor = QtGui.QTextEdit()
# fill the editor with text
# set the scroll to nth line
editor.show()

How can i achieve this?

Update

I managed to get it to show the nth line below:

cursor = QtGui.QTextCursor(editor.document().findBlockByLineNumber(n))
editor.moveCursor(QtGui.QTextCursor.End)
editor.setTextCursor(cursor)

For example, for n = 25, I get:

_______________________
.
.
.
.
25th line
_______________________

But I need him upstairs ...

+4
source share
1 answer

You almost have it. The trick is to move the current cursor to the bottom, and then reset the cursor to the target line. Then the view will automatically scroll to make the cursor visible:

editor.moveCursor(QtGui.QTextCursor.End)
cursor = QtGui.QTextCursor(editor.document().findBlockByLineNumber(n))
editor.setTextCursor(cursor)

, , :

editor.moveCursor(QtGui.QTextCursor.Start)
...

script:

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.edit = QtGui.QTextEdit(self)
        self.edit.setPlainText(
            '\n'.join('%04d - blah blah blah' % i for i in range(200)))
        self.button = QtGui.QPushButton('Go To Line', self)
        self.button.clicked.connect(self.handleButton)
        self.spin = QtGui.QSpinBox(self)
        self.spin.setRange(0, 199)
        self.spin.setValue(50)
        self.check = QtGui.QCheckBox('Scroll Top')
        self.check.setChecked(True)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.edit, 0, 0, 1, 3)
        layout.addWidget(self.button, 1, 0)
        layout.addWidget(self.spin, 1, 1)
        layout.addWidget(self.check, 1, 2)
        QtCore.QTimer.singleShot(0, lambda: self.scrollToLine(50))

    def scrollToLine(self, line=0):
        if self.check.isChecked():
            self.edit.moveCursor(QtGui.QTextCursor.End)
        else:
            self.edit.moveCursor(QtGui.QTextCursor.Start)
        cursor = QtGui.QTextCursor(
            self.edit.document().findBlockByLineNumber(line))
        self.edit.setTextCursor(cursor)

    def handleButton(self):
        self.scrollToLine(self.spin.value())
        self.edit.setFocus()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 100, 400, 300)
    window.show()
    sys.exit(app.exec_())
+4

Source: https://habr.com/ru/post/1660411/


All Articles