Qt Quick - How to use setContextProperties()

Viewed 462

I want to try out rootContext()->setContextProperties() instead of rootContext()->setContextProperty() because I read it is more efficient to bundle the properties instead of setting them X-times by yourself. Unfortunately I cannot find any good ressource on how to use it.

So e.g. in the main.cpp I have

ClassA a;
ClassB b;

Normally I would go for

engine.rootContext()->setContextProperty(&a, "classA");
engine.rootContext()->setContextProperty(&b, "classB");

So how can you syntactically correct sum this up and form it into a QVector<QQmlContext::PropertyPair>? The docs are really bare for this one.

A small example would be appreciated. Thanks!

1 Answers

This struct contains a property name and a property value. You can add multiple properties as a collection.

QSharedPointer<QQmlApplicationEngine> m_engine;
QQmlContext* m_ctxt;
m_engine->clearComponentCache();
m_engine.reset(new QQmlApplicationEngine, &QObject::deleteLater);
m_ctxt = m_engine->rootContext();
m_ctxt->setParent(m_engine.get());
QVector<QQmlContext::PropertyPair> qmlProperties;  

qmlProperties.push_back(QQmlContext::PropertyPair{"classA", QVariant::fromValue(objectA)});         

qmlProperties.push_back(QQmlContext::PropertyPair{"classB", QVariant::fromValue(objectB)});
    //add other context properties
m_ctxt->setContextProperties(qmlProperties);
m_engine->load(QUrl(QLatin1String("qrc:/qml/main.qml")));
Related