简体   繁体   中英

Load property from QML-file in C++

I'm building a plugin-system for my QML+C++ application. The plugins are QML-files. A qml-file could look like this:

Item { title: "Sexy Plugin" version: "1.0" }

How can I read title and version within C++?

Every QML item inherits QObject directly or indirectly, so you can use the meta system to read and write properties "dynamically".

QVariant QObject::property(const char * name) const  

Returns the value of the object's name property. If no such property exists, the returned variant is invalid.

If the item happens to be the root item, you can use QQuickItem * QQuickView::rootObject() const to get it, if not, you will have to set the objectName : QString property, avaiable for every QObject derived object and call findChild<QObject*>("name") from the root object.

The easiest wold be, to write a QuickItem in C++. Even when its just a small component, that just holds title and version. Then it is easily accessible within C++ and its the cleanest way, to decouple view and logic.Then you can just define properties with the well-known Q_PROPERTY Macro.

If you actually want to use only Qml-written components and don't want to write anything in C++, there is a solution mentioned at this page: http://qt-project.org/doc/qt-5/qtqml-cppintegration-interactqmlfromcpp.html

Quoting the relevant part from "Accessing Members of a QML Object Type from C++":

QQmlEngine engine;
QQmlComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

qDebug() << "Property value:" << QQmlProperty::read(object, "someNumber").toInt();
QQmlProperty::write(object, "someNumber", 5000);

qDebug() << "Property value:" << object->property("someNumber").toInt();
object->setProperty("someNumber", 100);

So QQmlProperty might help you.

As I don't know, what your goal is, I won't recommend anything. Anyway in my opinion, the first way of just writing the Item in C++ is in many cases much cleaner then trying to get the properties from Qml.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM