Gibt es eine andere Möglichkeit, diese Funktionalität zu erreichen?
Code: Select all
#ifndef SEARCHHIGHLIGHTER_H
#define SEARCHHIGHLIGHTER_H
#include
#include
#include
#include
#include
class SearchHighlighter : public QSyntaxHighlighter {
Q_OBJECT
public:
SearchHighlighter(QTextDocument *parent = nullptr)
: QSyntaxHighlighter(parent) {}
Q_INVOKABLE void setSearchTerm(const QString &term){
searchTerm = term;
rehighlight();
}
Q_INVOKABLE void setDocObj(QQuickTextDocument* textDocObj)
{
qDebug() textDocument();
setDocument(textDocObj->textDocument());
}
protected:
void highlightBlock(const QString &text) override {
if (searchTerm.isEmpty())
return;
QTextCharFormat fmt;
fmt.setForeground(Qt::red);
fmt.setBackground(Qt::yellow);
QRegularExpression re(QRegularExpression::escape(searchTerm),
QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatchIterator i = re.globalMatch(text);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QSyntaxHighlighter::setFormat(match.capturedStart(), match.capturedLength(), fmt);
}
}
private:
QString searchTerm;
};
#endif // SEARCHHIGHLIGHTER_H
Code: Select all
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreated,
&app,
[url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
},
Qt::QueuedConnection);
SearchHighlighter *hl = new SearchHighlighter();
engine.rootContext()->setContextProperty("searchHighlighter", hl);
engine.load(url);
return app.exec();
}
Code: Select all
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
ApplicationWindow {
visible: true
width: 600
height: 400
ColumnLayout {
anchors.fill: parent
TextField {
id: searchBox
Layout.leftMargin: 10
Layout.topMargin: 10
placeholderText: "Search..."
onTextChanged: searchHighlighter.setSearchTerm(text)
}
TextEdit {
id: editor
Layout.fillHeight: true
Layout.fillWidth: true
Layout.leftMargin: 10
font.pixelSize: 20
wrapMode: TextEdit.Wrap
Component.onCompleted: {
searchHighlighter.setDocObj(editor.textDocument)
}
}
}
}