PDA

View Full Version : Problem with auto indent text while typing



Fred
24th August 2017, 14:46
I'm trying to implement in a project an auto indent feature. Headings and lists should automatically indented while you typing. I have done this in a QTextEdit subclass and this approach works but it makes Undo/Redo non functional from the QTextEdit. I found out that textCursor().setBlockFormat is the problem but without the text wouldn't indented. Can anybody help me with this?

Here the source of the keyPressEvent and here (https://www.file-upload.net/download-12675158/untitled.zip.html) a full working example.


void subedit::keyPressEvent( QKeyEvent *event )
{
QTextEdit::keyPressEvent( event );

QString text = textCursor().block().text();
QTextBlockFormat textBlockFormat = textCursor().blockFormat();

int indent( 1 );
if ( text.startsWith( "#" ) )
indent = 0;
else if ( text.indexOf( QRegularExpression( "(^[-*+] )|(^[\\d+]\\. )" ) ) == 0 )
indent = 2;

textBlockFormat.setIndent( indent );
textCursor().setBlockFormat( textBlockFormat );
}

wysota
28th August 2017, 10:14
Why does it make undo/redo non-functional? What is the behaviour you observe?

Fred
28th August 2017, 10:51
When you insert some returns, go back to top of the document and write some text and press then several times CTRL+Z. All what you get is that the cursor goes one line down when you press the shortcut (the same way as you use the arrow down key), but no undo. Redo (CTRL+SHIFT+Z) has absolutely no effect, the cursor keeps at the current position.