Rich Hoffman
Rich Hoffman

Reputation: 762

Unable to set QQmlApplicationEngine rootContext Property

I've got the following code that I thought should make a "backend" C++ object available in QML elements of my GUI, but seems to be failing, resulting in a property of my QML objects that is null.

    //Initialize the engine, register the Data_Client object and set the "client" property
    QQmlApplicationEngine engine;
    QQmlContext *context = engine.rootContext();
    const QUrl url(QStringLiteral("qrc:/qml/gui.qml"));

    qmlRegisterType<Data_Client>("uri", 1, 0, "Data_Client");
    qmlRegisterType<StatusObject>("uri", 1, 0, "StatusObject");

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    Data_Client client();
    //Make the Data_Client accessible in the engine root context so its available to all component instances
    context->setContextProperty("client", &client); 
    return app.exec();

In the ApplicationWindow item of the gui.qml file, the client property is declared and various connections are declared with the "client" as the target:

property Data_Client client
//...
Connections {
        target: client
        onNew_data:{ 
        //...
        }

In the Data_Client C++, I call emit new_data(QString("test")); but never trigger the handler in the QML. This formerly worked and I thought was so fundamentally simple that I was good to go, so I haven't determined what I may have broken. My operating theory right now is that this is not setting the client property of the rootContext, but there's no check I can make at runtime, is there? Is there something obvious that I'm missing?

Upvotes: 1

Views: 1199

Answers (1)

JarMan
JarMan

Reputation: 8287

In theory, setContextProperty can be called at any time, but any QML files that are already loaded at that time probably will not see that new property. QML files loaded after that point will see it. So calling setContextProperty before you call engine.load() should fix the problem for you.

Upvotes: 3

Related Questions