Problem in Check the highlighted string in QPlainTextEdit
-
I have a QPlainTextEdit which have a highlighted piece of string in it using this code to make the highlight
QString str = "an"; ui->plainTextEdit->setPlainText("Hello world this\nan example to test"); int begin = ui->plainTextEdit->toPlainText().indexOf(str); // get index of word start int end = begin + str.size(); // end of word qDebug() << begin << " " << end << endl; QTextCharFormat fmt; fmt.setBackground(Qt::yellow); // a char format //move on it and start highlight this word QTextCursor cursor(ui->plainTextEdit->document()); cursor.setPosition(begin,QTextCursor::MoveAnchor); cursor.setPosition(end,QTextCursor::KeepAnchor); cursor.setCharFormat(fmt);and this code to check the highlighted word if it's highlighted or not
QString str = "an"; int begin = ui->plainTextEdit->toPlainText().indexOf(str); int end = begin + str.size(); QTextCursor cursor(ui->plainTextEdit->document()); cursor.setPosition(begin,QTextCursor::MoveAnchor); cursor.setPosition(end,QTextCursor::KeepAnchor); QTextCharFormat fmt = cursor.charFormat(); if (fmt.background() == Qt::yellow) { qDebug() << "YES highlighted"; } else { qDebug() << "NO Not highlighted"; }it works fine
The problem is when I begin from early start if i make begin - 10 for example it ouput "yes highlighted" which is wrong so if I make begin = 0 and end stop at the position of the highlighted word it say YES if i increase the end it say no so it work from one side only
but it work when I extend the end if i make for example end + 10 it say no
why it make that and how to fix it
this the example of begin which have the problemQString str = "an"; int begin = 0; // start from 0 which all not highlighted int end = ui->plainTextEdit->toPlainText().indexOf(str); + str.size(); and stop and end of the highlighted word QTextCursor cursor(ui->plainTextEdit->document()); cursor.setPosition(begin,QTextCursor::MoveAnchor); cursor.setPosition(end,QTextCursor::KeepAnchor); QTextCharFormat fmt = cursor.charFormat(); if (fmt.background() == Qt::yellow) { qDebug() << "YES"; // it ouput yes because just from the start to end contains a highlighted word } else { qDebug() << "NO"; }Thanks in advance
-
Hi,
Out of curiosity, any reasons for not using a QSyntaxHighlighter ?