I managed to find out myself. Here is the code, in case others might want the same:
C++
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStringList>
#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>
int main(int argc, char ** argv)
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/view.qml"));
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreated,
&app,
[url](QObject *obj, const QUrl &objUrl) {if (!obj && url == objUrl) QCoreApplication::exit(-1);}, Qt::QueuedConnection);
engine.load(url);
// get the root object of the loaded QML
QList<QObject*> root_objects(engine.rootObjects());
QStringList projectList = {
"Project 1",
"Project 2",
"Project 3",
"Project 4"
};
const QObjectList& children(root_objects[0]->children());
if (!children.isEmpty())
{
QList<QObject*> lists(root_objects[0]->findChildren<QObject*>("listViewProjects"));
if (!lists.isEmpty())
lists.first()->setProperty("model", QVariant::fromValue(projectList));
}
return app.exec();
}
QML
import QtQuick 2.4
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.5
Window {
id: window
visible: true
width: 640
height: 480
title: qsTr("ListView")
ListView {
id: listViewProjects
objectName: "listViewProjects"
anchors.fill: parent
delegate: Item {
id: project
required property string modelData
required property int index
height: 30
width: parent.width
Text {
anchors.verticalCenter: parent.verticalCenter
text: parent.modelData
}
MouseArea {
anchors.fill: parent
onClicked: listViewProjects.currentIndex = parent.index
}
}
highlight: Rectangle { color: "lightsteelblue"; radius: 2 }
focus: true
}
}
It also shows how to use the index variable for setting the selection with the mouse: once a required property is declared (modelData), you must declare all properties you intend to use. This is not shown in any other example I could find. If you fail to do this, index is undefined.