Important: Please read the Qt Code of Conduct -

Stop QTextCursor from resetting undo stack

  • I have a function that check previous line and insert text to the QPlainTextEdit QTextCursor. Problem with my function is it resets the undo stack of the QPlainTextEdit. Is there a way to add my changes to the undo stack instead of resetting it?

    This is how I'm currently doing it:

        QTextBlock textBlock = ui->noteText->textCursor().block();
        QString prevLine = textBlock.previous().text();
        if (checkListItem(prevLine)) {
            if (textBlock.text().length() == 0) {
                int spaceCount = getSpaceCount(prevLine);
                QString newLine = QString("").leftJustified(spaceCount, ' ');
                if (checkUnorderedListItem(prevLine)) {
                    newLine += "* ";
                } else {
                    newLine += getNextNumber(prevLine) + ". ";


    Because of how my function works, if the previous line checks true and current line is empty when undoing it inserts new text again into the current line.

    I had to create an event filter and override ControlModifier + 'Z' event to make it work.