【发布时间】:2016-10-02 14:25:24
【问题描述】:
我想在 QPlainTextEdit 中搜索从当前光标到结尾的字符串。如果什么也没找到,我想从头开始搜索。只有在这个阶段,如果没有找到,就会出现一条消息。 这是代码:
void BasicEdit::findString(QString s, bool reverse, bool casesens, bool words) {
QTextDocument::FindFlags flag;
if (reverse) flag |= QTextDocument::FindBackward;
if (casesens) flag |= QTextDocument::FindCaseSensitively;
if (words) flag |= QTextDocument::FindWholeWords;
QTextCursor cursor = this->textCursor();
if (!find(s, flag)) {
//nothing is found | jump to start/end
cursor.movePosition(reverse?QTextCursor::End:QTextCursor::Start);
setTextCursor(cursor); //!!!!!!
if (!find(s, flag)) {
//no match in whole document
QMessageBox msgBox;
msgBox.setText(tr("String not found."));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
}
}
问题出在setTextCursor(cursor);行
- 没有这一行,搜索不会从头/尾继续
- 有了这一行,一切都很好,除了找不到字符串时,光标位于文档的开头/结尾,并且用户在文档中的当前位置丢失了。
如何在文档中搜索字符串,如果没有找到不改变当前位置?
更新
感谢 IAmInPLS,代码如下所示。
我为verticalScrollBar 添加了保值。
即便如此,当没有找到任何东西时也会有短暂的闪烁:cursor.movePosition(reverse?QTextCursor::End:QTextCursor::Start);
我们怎样才能摆脱它? 怎么可能看起来像专业编辑? 是否可以创建另一个不可见的 QPlainTextEdit 元素在其中进行搜索?
void BasicEdit::findString(QString s, bool reverse, bool casesens, bool words)
{
QTextDocument::FindFlags flag;
if (reverse) flag |= QTextDocument::FindBackward;
if (casesens) flag |= QTextDocument::FindCaseSensitively;
if (words) flag |= QTextDocument::FindWholeWords;
QTextCursor cursor = this->textCursor();
// here we save the cursor position and the verticalScrollBar value
QTextCursor cursorSaved = cursor;
int scroll = verticalScrollBar()->value();
if (!find(s, flag))
{
//nothing is found | jump to start/end
cursor.movePosition(reverse?QTextCursor::End:QTextCursor::Start);
setTextCursor(cursor);
if (!find(s, flag))
{
// word not found : we set the cursor back to its initial position and restore verticalScrollBar value
setTextCursor(cursorSaved);
verticalScrollBar()->setValue(scroll);
QMessageBox msgBox(this);
msgBox.setText(tr("String not found."));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
}
}
【问题讨论】:
-
在开头保存初始光标位置,如果没有找到则恢复。
标签: c++ qt find qplaintextedit qtextcursor