Get the last two characters written in a QTextEdit
-
I want to get the last two characters written in a QTextEdit. I tried the following
void MainWindow::onTextChanged() { QTextCursor c = textEdit->textCursor(); c.setPosition(textEdit->cursor().pos().x()); c.setPosition(textEdit->cursor().pos().x() - 2, QTextCursor::KeepAnchor); textEdit->setTextCursor(c); qDebug() << textEdit->textCursor().selectedText(); }
Which partially works since I get the last two characters of the text but I also highlight them and rewrite them. I want it to be impossible for the user to see or know that the last two characters were retrieved and I also want to continue to write without overwriting the last two characters in my text!
-
Would it alread help to remove
textEdit->setTextCursor(c);
and instead useqDebug() << c.selectedText();
? -
Depending on how many characters I've got in my QTextEdit I get one of these two messages
QTextCursor::setPosition: Position '458' out of range QTextCursor::setPosition: Position '460' out of range
or if there is quite little text
"" "" ""
Removing "textEdit->setTextCursor(c);" fixed the issue of the QTextEdit highlighting and removing text but makes the printing of the last two characters impossible, AKA it gives one of the two errors I mentioned above.
-
Edit: Wrong code, see below
QTextCursor cur = textEdit->textCursor(); newCur.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,2); qDebug() << textEdit->textCursor().selectedText(); newCur.movePosition(QTextCursor::PreviousCharacter,QTextCursor::MoveAnchor,2);
-
@VRonin I tried
QTextCursor cur = textEdit->textCursor(); cur.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,2); qDebug() << textEdit->textCursor().selectedText(); cur.movePosition(QTextCursor::PreviousCharacter,QTextCursor::MoveAnchor,2);
but it gave me
"" "" "" "" ""
in the console, not the last two characters... It did solve the "out of range" issue though!
-
@VRonin it worked! thanks!
void MainWindow::onTextChanged() { QTextCursor cur = textEdit->textCursor(); cur.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,2); qDebug() << cur.selectedText(); }
-
QString str = textEdit->toPlainText(); QString targetChars = str.mid(textEdit->textCursor().columnNumber() -2 ,2); qDebug() <<targetChars;