将 QTextCursor 移动到最后的问题

Ara*_*emi 6 qt4 qtextdocument

我正在尝试在我正在编写的编辑器中实现简单的文本搜索。一切都很好,直到出现这个问题!我正在尝试在这里实现向后搜索。过程是:向后查找主题,如果没有找到,蜂鸣一声,如果再次按下查找按钮,则到文档末尾,重新进行查找。“reachedEnd”是一个 int,定义为编辑器类的私有成员。这是执行向后搜索的函数。

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是光标没有移动到最后!它返回 False,这意味着失败。这怎么会失败?!!提前致谢。

lim*_*mbo 7

由于这个问题得到了一些观点,而且它似乎是一个常见问题,我认为它值得一个答案(尽管作者肯定已经想通了)。

从文档:

QTextCursor QPlainTextEdit::textCursor() const
返回代表当前可见光标的 QTextCursor 的副本。请注意,返回游标的更改不会影响 QPlainTextEdit 的游标;使用 setTextCursor() 更新可见光标。

所以你得到了它的副本,这样做cursor.movePosition(QTextCursor::End);是行不通的。

我所做的是:

QTextCursor newCursor = new QTextCursor(document);
newCursor.movePosition(QTextCursor::End);
curTextPage()->setTextCursor(newCursor);
Run Code Online (Sandbox Code Playgroud)

  • 如何使用“QTextEdit”来做到这一点? (2认同)