Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in Moving QTextCursor to the End

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.

like image 876
Aozi Avatar asked Jul 22 '11 06:07

Aozi


2 Answers

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);
like image 82
limbo Avatar answered Oct 07 '22 00:10

limbo


If I simplify your code like this:

if (!cursor.isNull()) {
   // (...)
}
else {
    // (...)
    cursor.movePosition(QTextCursor::End);
    // (...)
}

...I see that you call the movePosition() function while the cursor.isNull() condition is true. Maybe this is the reason it doesn't work...

like image 45
Fivos Vilanakis Avatar answered Oct 06 '22 23:10

Fivos Vilanakis