Problem in Moving QTextCursor to the End

Aozi picture Aozi · Jul 22, 2011 · Viewed 9.3k times · Source

I'm trying to implement a simple text search in an editor i'm writing. Everything have been fine until this problem! I'm trying to implement a backward search here. The procedure is: look for the subject backward, if not found, beep once, and if find button was pressed again, go to the end of the document, and do the search again. "reachedEnd" is an int, defined as a private member of the editor class. Here's the function that does the backward search.

void TextEditor::findPrevPressed() {
    QTextDocument *document = curTextPage()->document();
    QTextCursor    cursor   = curTextPage()->textCursor();

    QString find=findInput->text(), replace=replaceInput->text();


    if (!cursor.isNull()) {
        curTextPage()->setTextCursor(cursor);
        reachedEnd = 0;
    }
    else {
        if(!reachedEnd) {
            QApplication::beep();
            reachedEnd = 1;
        }
        else {
            reachedEnd = 0;
            cursor.movePosition(QTextCursor::End);
            curTextPage()->setTextCursor(cursor);
            findPrevPressed();
        }
    }
}

The problem is that cursor doesn't move to the end! And it returns False, which means failure. How can this fail?!! Thanks in advance.

Answer

limbo picture limbo · Jun 1, 2016

Since this question got some views and it appears to be a common problem, I think it deserves an answer (even though the author most surely figured it out).

From the documentation:

QTextCursor QPlainTextEdit::textCursor() const
Returns a copy of the QTextCursor that represents the currently visible cursor. Note that changes on the returned cursor do not affect QPlainTextEdit's cursor; use setTextCursor() to update the visible cursor.

So you got a copy of it and by doing cursor.movePosition(QTextCursor::End); it wouldn't work.

What I did is:

QTextCursor newCursor = new QTextCursor(document);
newCursor.movePosition(QTextCursor::End);
curTextPage()->setTextCursor(newCursor);