我正在寻找一种在QML对象树中的某些对象范围内添加属性的方法。
file.qml:
import QtQml 2.0
QtObject {
property var test1: QtObject {
objectName: "child1"
property string color: environment.color
}
property var test2: QtObject {
objectName: "child2"
property string color: environment.color
}
}
main.cpp:
#include <QtCore>
#include <QtQml>
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
QQmlEngine engine;
QQmlComponent component(&engine,QUrl::fromLocalFile("file.qml"));
QObject* object = component.beginCreate(engine.rootContext());
QObject* child1 = object->findChild<QObject*>("child1", Qt::FindChildrenRecursively);
QObject* child2 = object->findChild<QObject*>("child2", Qt::FindChildrenRecursively);
QQmlPropertyMap env1;
QQmlPropertyMap env2;
env1["color"] = "green";
env2["color"] = "blue";
// Now I want to make object1 available for child1
// and object2 available for child2.
// But I can't do this:
// qmlContext(test1)->setContextProperty("environment", env1);
// qmlContext(test2)->setContextProperty("environment", env2);
component.completeCreate();
if (!component.errors().isEmpty()) {
qDebug() << component.errorString();
}
Q_ASSERT(child1->property("color") == QString("green"));
Q_ASSERT(child2->property("color") == QString("blue"));
qDebug() << "It works";
}
我承认上面的例子看起来有些奇怪。这是example I posted in the Qt forum的简化版本。