i have a cpp struct which have so much fields
struct CloudMusicSongList{ ... };
and i want use it in qml in order input some infomation to it's instance, but i don't want to create a qobject derived class,and create a lot of qproperty ... i seache in google and get this code snippt from this
i don't know whether it is the X Y problem.
somebody can help? thanks
i want create a bindingProxy template class which twoway bindable in qml i think it should equivalence dynamicObject in wpf
CodePudding user response:
Based on CloudMusicSongList
I'm assuming the thing that you have is a list/array. There are quite a number of ways of exposing this to QML.
- QQmlListProperty - https://doc.qt.io/qt-6/qqmllistproperty.html
- QAbstractListModel - https://doc-snapshots.qt.io/qt6-dev/qabstractlistmodel.html
- QVariant, QVariantList, and/or QVariantMap - https://doc-snapshots.qt.io/qt6-dev/qvariant.html
- QObject / Q_OBJECT - create a new QML component and register it
- Q_GADGET - register your C structure (good for access the class in a signal, but, QML/JS cannot copying it into a Javascript object, only good for the duration of the signal)
QQmlListProperty is a list of QObjects. It requires the underlying QObject be registered, but, allows you to create/manage and walk through a list of the results. The list is owned, usually by another QObject. e.g. we could have a QmlFile object, then implement a QmlFileSystem object that can return a list of QmlFiles.
QAbstactListModel can be used in places where a model is required, e.g. ListView.
QVariant, QVariantList and QVariantMap is the simplest way of creating a Javascript object in QML. The advantage is you do not have to register anything, but, the disadvantage is you do not get intellisense.
QVariant getBooks() {
QVariantList books;
QVariantMap book1;
book1["title"] = QString("Lord of the Rings");
QVariantMap book2;
book2["title"] = QString("The Hobbit");
books.append(book2);
return books;
// results in QML/JS:
// [ { "title": "Lord of the Rings" },
// { "title" : "The Hobbit" } ]
}