Hey,
I'm trying to catch the users input in a QTextEdit and check for illegal characters.
I catch the signal "textChanged()" and check the input (edit->toPlainText()) for illegal characters.
If some illegal characters are found, I replace or remove them and set the new text (edit->setPlainText(QString)).
Now my problem is the cursor position. I found out that calling QTextEdit::setPlainText(QString) sets a new QTextCursor at position '0'.
I manage this by saving the QTextCursor's recent position (before changing input) and set this position to the new QTextCursor, like this:
this->blockSignals(true);
QString input
= this
->toPlainText
();
// ... some checks and replaces with input
int cursorPos = this->textCursor().position();
this->setPlainText(input); // this deletes the previous cursor
cursor.setPosition(cursorPos);
this->setTextCursor(cursor);
this->blockSignals(false);
this->blockSignals(true);
QString input = this->toPlainText();
// ... some checks and replaces with input
QTextCursor cursor = this->textCursor();
int cursorPos = this->textCursor().position();
this->setPlainText(input); // this deletes the previous cursor
cursor.setPosition(cursorPos);
this->setTextCursor(cursor);
this->blockSignals(false);
To copy to clipboard, switch view to plain text mode
This works great. What I don't under stand is, why the following code (exactly the same commands, only different order) doesn't work:
this->blockSignals(true);
QString input
= this
->toPlainText
();
// ... some checks and replaces with input
int cursorPos = this->textCursor().position();
cursor.setPosition(cursorPos);
this->setPlainText(input); // this deletes the previous cursor
this->setTextCursor(cursor);
this->blockSignals(false);
this->blockSignals(true);
QString input = this->toPlainText();
// ... some checks and replaces with input
QTextCursor cursor = this->textCursor();
int cursorPos = this->textCursor().position();
cursor.setPosition(cursorPos);
this->setPlainText(input); // this deletes the previous cursor
this->setTextCursor(cursor);
this->blockSignals(false);
To copy to clipboard, switch view to plain text mode
I would understand that if "cursor" was a pointer, but it isn't!! How can QTextEdit recognize that I set the new cursor position before setting new text?
I would really appreciate a good explanation of this strange behaviour...
Thank you in anticipation!
Binary
Bookmarks