I am working on a QtQuick 2.0
presentation and I would like to embed some code samples. is it possible easily to create a syntax highlighting qml element.
C
in your app file:
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQuickTextDocument* doc = childObject(engine, "textEditor", "textDocument");
Q_ASSERT(doc != 0);
// QSyntaxHighlighter derrived class
MySyntaxHighlighter* parser = new MySyntaxHighlighter(doc->textDocument());
// use parser, see QSyntaxHighlighter doc...
int ret = app.exec();
delete parser;
return ret;
The template function to get child objects (returns the first occurence of objectName, so use unique names to identify objects in your qml files) :
template T childObject(QQmlApplicationEngine& engine,
const QString& objectName,
const QString& propertyName)
{
QList rootObjects = engine.rootObjects();
foreach (QObject* object, rootObjects)
{
QObject* child = object->findChild(objectName);
if (child != 0)
{
std::string s = propertyName.toStdString();
QObject* object = child->property(s.c_str()).value();
Q_ASSERT(object != 0);
T prop = dynamic_cast(object);
Q_ASSERT(prop != 0);
return prop;
}
}
return (T) 0;
}
in your qml file use a TextEdit (inside a Flickable or whatever you want) with the objectName property correctly set:
....
TextEdit {
id: edit
objectName: "textEditor"
width: flick.width
height: flick.height
focus: true
font.family: "Courier New"
font.pointSize: 12
wrapMode: TextEdit.NoWrap
onCursorRectangleChanged: flick.ensureVisible(cursorRectangle)
}
....