Nominate our 2022 Qt Champions!

Ideas to make a QTextEdit partially read-only?

  • I have a QTextEdit and I need it to be partially read-only. For partially I mean that text previously available in the editor should not be editable (deleted, replaced, or new text typed or pasted in between ect..) and any new input (either pasted or typed by keyboard) should go on the last line.
    To put it more simply, a terminal-like behaviour.

    I was thinking about checking the cursor position and responding to events such as keyPressEvent, keyReleaseEvent and others, but looks to me like prone-to-error and extremely painful...

    Do you have any ideas?

  • You can make sure the new text is entered on the last line by moving the cursor to the end of the document before adding the text:


    There is a signal you can monitor to see if the cursor position has changed (i.e. someone clicks in the middle):


    That signal and boolean QTextCursor::atEnd() would problably be all you need.

    You could make it read only and overload the keyPress() events in a subclass. I am not sure if this would work (depends if a read only QTextEdit can get input focus).

    I use something like this to store the state if I am updating or changing the contents (so it doesn't appear to move). It uses the QTextCuror:

    QTextCursor TextCursor;
    int TextCursorPosition;
    int VerticalScrollbarPosition;
    int HorizontalScrollbarPosition;

    TextCursorPosition = d_MeasurementText->textCursor().position();
    VerticalScrollbarPosition = d_MeasurementText->verticalScrollBar()->value();
    HorizontalScrollbarPosition = d_MeasurementText->horizontalScrollBar()->value();

    // text contents erased and updated

    TextCursor = d_MeasurementText->textCursor();


  • [quote author="Rondog" date="1425009774"]
    You could make it read only and overload the keyPress() events in a subclass. I am not sure if this would work (depends if a read only QTextEdit can get input focus).
    I have just tried and it looks like the keyPressEvent will be called on keypress, no matter if it's read-only or not. Moreover, even if the QTextEdit is not read-only, by reimplementing the keyPressEvent it will stop the QTextEditor from writing the character in the text area (right-click->paste will still insert text at cursor position if not read-only).

    It's not an easy task, but I expected it to be a bit harder :D I will try working on this path, see if something useful comes out.
    Thank you very much for help, Rondog!

  • You can add QTextEdit::keyPressEvent(event) to forward it to the base class. It will work properly and handle all key events and you have the option to add something else to it.

    So something like this:

    void MyEdit::keyPressEvent(QKeyPressEvent *event)

    // make sure cursor is at the end of the document
    // or something else related to the key


Log in to reply