Problem in Moving QTextCursor to the End

元气小坏坏 提交于 2019-12-12 14:12:45

问题


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.


回答1:


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);



回答2:


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...



来源:https://stackoverflow.com/questions/6786641/problem-in-moving-qtextcursor-to-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!