为什么此代码一旦找到就不会突出显示搜索词?

时间:2012-01-02 07:56:32

标签: c++ qt4 find text-editor

以下代码在找到时不会突出显示搜索字词。实际上,在按下“下一步”按钮后,光标会从QPlainTextEdit(称为ui-> gt Editor)中消失。是什么导致了它?

void TextEditor::findNextInstanceOfSearchTerm()
{
    QString searchTerm = this->edtFind->text();

    if(this->TextDocument == NULL)
    {
        this->TextDocument = ui->Editor->document();
    }


    QTextCursor documentCursor(this->TextDocument);

    documentCursor = this->TextDocument->find(searchTerm,documentCursor);

    if(!documentCursor.isNull())
    {
        documentCursor.select(QTextCursor::WordUnderCursor);

    }else
    {
        ui->statusbar->showMessage("\""+searchTerm+"\" could not be found",MESSAGE_DURATION);

    }
}

2 个答案:

答案 0 :(得分:2)

首先,每次按下下一个按钮时,您的代码都会在文档的开头创建一个新光标,因此您将始终从头开始搜索。其次,您必须了解您操作的光标与QPlainTextEdit中的光标无关:您操纵副本。如果要影响文本编辑,则必须使用setTextCursor修改其光标。这是一个有效的解决方案:

void TextEditor::findNextInstanceOfSearchTerm()
{
    QString searchTerm = this->edtFind->text();

    if(this->TextDocument == NULL)
    {
        this->TextDocument = ui->Editor->document();
    }

    // get the current cursor
    QTextCursor documentCursor = ui->Editor->textCursor();

    documentCursor = this->TextDocument->find(searchTerm,documentCursor);

    if(!documentCursor.isNull())
    {
        // needed only if you want the entire word to be selected
        documentCursor.select(QTextCursor::WordUnderCursor);

        // modify the text edit cursor
        ui->Editor->setTextCursor(documentCursor);
    }
    else
    {
        ui->statusbar->showMessage(
            "\""+searchTerm+"\" could not be found",MESSAGE_DURATION);
    }
}

作为旁注,您可能想知道QPlainTextEdit提供了find方法,因此这可能是实现您想要的更简单的方法:

void TextEditor::findNextInstanceOfSearchTerm()
{
    QString searchTerm = this->edtFind->text();

    bool found = ui->Editor->find(searchTerm);

    if (found)
    {
        QTextCursor cursor = ui->Editor->textCursor();
        cursor.select(QTextCursor::WordUnderCursor);
        ui->Editor->setTextCursor(cursor);
    }
    else
    {
        // set message in status bar
    }
}

答案 1 :(得分:1)

  1. 使用QTextCursor::EndOfWord
  2. 使用QPlainTextEdit::setExtraSelections选择/突出显示QPlainTextEdit
  3. 中的内容

    您已经拥有了可突出显示单词的光标,但您没有将其应用于文本编辑