Extract Context Properties from C++ Code
-
We have a set of external variables that will be available in QML via the setContextProperty() and the Q_Property Makro.
We have a situation involving possibly thousands of variables that could possibly be used in QML by a User. (The User will work with the QtCreator in QML Design mode). It would be very nice to know in advance which of the variables the user has actually used in his qml file.
Is there a way to achieve this? As far as I know, contextProperties have to be set, before the QML Source is given. Is word search in my qml file the only option?Thank you
-
If you mean detection at runtime, then your Q_PROPERTYies just need to add some check in their setter. Example:
@
// pseudo code :)
class MyClass : public QObject {
Q_PROPERTY(READ myProp WRITE setProp)QMap<QString, bool> usedPropertiesMap; // sets true for properties in use
setProp(value) {
usedPropertiesMap.insert("myProp", true);
myProp = value;
emit myPropChanged();
}
}
@Same goes for getter, depending on your needs. I have to say I'm not sure that is what you mean, though.
-
Thank you for the reply.
I have the c++ side and the qml side of the code. A potential user would modify a qml file. I need to find out which variables he used in the qml code before I do this:
@for(std::vector<MyListElement*>::iterator it = myList.begin() ; it != myList.end(); ++it)
{ viewer.rootContext()->setContextProperty(QString((*it)->strGetName()),*it);
}@and set thousands of potential variables as context properties. Maybe the person who edited the qml file used only five variables.--
(Every MyListElement has a Q_Property that can be used by the person who creates the qml file. Eventually these properties point to variables on a PLC)
The pseudo code would track my properties on he c++ side. I guess want to know if I can analyze a qml file or if I need to redesign something.
Thanks
-
OK. Parsing the QML is an option, but probably too cumbersome. You would need to do it before loading the QML. Once you load it, it will throw errors on properties that were not included, which is not what you want.
What about a "just in time" property inclusion? Instead of adding numerous Q_PROPERTYies, provide an object with something like:
@
Q_INVOKABLE QVariant getProperty(const QString &propertyName);
Q_INVOKABLE void setProperty(const QString &propertyName, QVariant value);
@But this way you will loose all the NOTIFY goodness.
Or you could divide your properties into modules and include them in QML using import statements.