Pregunta

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?

¿Fue útil?

Solución

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

void QTextCursor::deletePreviousChar()

(Edit)as code:

QTextCursor  cursor = ui->textEdit->textCursor();
ui->textEdit->setTextCursor( cursor );
cursor.deletePreviousChar();

Otros consejos

If number exceeds the limit or wrong character is typed I'm using:

ui->textEdit->textCursor().deletePreviousChar();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top