pythoninsertpyqtappendqtextedit

How to insert text at the top of a QTextEdit widget?


I have a simple QTextEdit form which I am using as a sort of log. Events are written down into the form, so the user can review history events. I am using textEdit.append() to add new lines to the form. However, textEdit.append(), appends the text to the end of the buffer, so the newest events are shown on the bottom. Is there a reasonable way to append to the beginning, so that the newest events are shown on the top?


Solution

  • You can use the insertPlainText method to insert text anywhere in the current text. Place a cursor to specify where the text is to be inserted. In your case you'd place it at the start:

    from PyQt5.QtGui import QTextCursor
    
    # set the cursor position to 0
    cursor = QTextCursor(textEdit.document())
    # set the cursor position (defaults to 0 so this is redundant)
    cursor.setPosition(0)
    textEdit.setTextCursor(cursor)
    
    # insert text at the cursor
    textEdit.insertPlainText('your text here')