This example lets you search with arbitrary regular expressions inside a QTextBrowser. It will present matches as selected text.
{
public:
struct TextCursorPosData : public Pos::PosData
{
bool equals(Pos::PosData * other) const {
return cursor == dynamic_cast<TextCursorPosData*>(other)->cursor;
}
};
TextDocumentSearchable(QTextBrowser *b) :
QObject(b), br(b), doc(br->document()) { }
Pos searchFind(
const QString& querystring,
const Pos& fromPos,
bool forward)
{
if (fromPos.valid()) {
pos = fromPos.data<TextCursorPosData>()->cursor;
pos.
movePosition(forward?QTextCursor::Right:QTextCursor::Left);
}
rx.setCaseSensitivity(querystring.
contains(
QRegExp(
"[A-Z]"))?Qt::CaseSensitive:Qt::CaseInsensitive);
if (!forward && pos.
isNull()) {
}
return Pos();
}
pos.
movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, rx.matchedLength());
Pos foundPos = Pos();
foundPos.posdata = new TextCursorPosData(pos);
return foundPos;
}
void searchAborted()
{
}
void searchMoveToPos(const Pos& p)
{
if (p.valid())
br->setTextCursor(p.data<TextCursorPosData>()->cursor);
else
}
private:
QTextBrowser *br;
};
You could then use that class as follows:
QTextBrowser *textBrowser = new QTextBrowser(this);
textBrowser->setPlainText(...);
TextDocumentSearchable * s = new TextDocumentSearchable(textBrowser);