I have a QTextEdit control. It has a maximum limit (maximum number of characters it can hold). To implement this I have connected a slot to the textChanged() signal which removes the extra character when the total number of characters exceeds the allowed maximum.
With this I have some problems dealing with the cursor position. Can anyone tell me how to retain the cursor position in QTextEdit?
On your slot:
If num of chars exceeds maximum:
Ask the QTextEdit for the Cursor:
QTextCursor QTextEdit::textCursor() const
Set the return value as your textEdit cursor (cause it returns a copy). From doc:
Returns a copy of the QTextCursor that represents the currently visible cursor. Note that > changes on the returned cursor do not affect QTextEdit's cursor; use setTextCursor() to > update the visible cursor.
void QTextEdit::setTextCursor(const QTextCursor & cursor)
Ask the cursor to delete last char
(Edit)as code:
QTextCursor cursor = ui->textEdit->textCursor();
ui->textEdit->setTextCursor( cursor );
cursor.deletePreviousChar();