2

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?

Philip Allgaier
  • 3,505
  • 2
  • 26
  • 53
asitdhal
  • 621
  • 2
  • 7
  • 15

2 Answers2

6

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();
trompa
  • 1,967
  • 1
  • 18
  • 26
  • QTextCursor cursor = ui->textEdit->textCursor(); ui->textEdit->setTextCursor( cursor ); what is the point of writing the above two line ? Its only getting the cursor position and setting it . – asitdhal Jun 19 '13 at 08:50
  • Documentation: `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.` – trompa Jun 19 '13 at 09:05
2

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

ui->textEdit->textCursor().deletePreviousChar();
SPirev
  • 21
  • 2