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 a full working example.
void subedit
::keyPressEvent( QKeyEvent *event
) {
QString text
= textCursor
().
block().
text();
int indent( 1 );
if ( text.startsWith( "#" ) )
indent = 0;
else if ( text.indexOf( QRegularExpression( "(^[-*+] )|(^[\\d+]\\. )" ) ) == 0 )
indent = 2;
textBlockFormat.setIndent( indent );
textCursor().setBlockFormat( textBlockFormat );
}
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 );
}
To copy to clipboard, switch view to plain text mode
Bookmarks