setContextProperty not setting context properly

  • Okay, the way I understand it, I have to set the context properties before I load a qml file. So I did this:

    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        //QQuickView view(QUrl(QStringLiteral("qrc:/main.qml")));
        //QQuickItem *item = view.rootObject();
        Controller control; // qobject based
        QQmlApplicationEngine engine;
        QQmlContext *context = new QQmlContext(engine.rootContext());
        context->setContextProperty("controller", &control);
        //if (engine.rootObjects().isEmpty())
        //    return -1;
        QQmlComponent component(&engine);
        QQuickItem *tobj;
        if (component.isReady()){
            QObject *myObject = component.create();
            tobj = qobject_cast<QQuickItem*>(myObject);
            qWarning() << component.errorString();
        //QQuickItem *item = engine.rootObjects();
        for(auto item: engine.rootObjects())
            QObject::connect(item, SIGNAL(operateSig()),
                                 &control, SIGNAL(operate()));
        return app.exec();

    QML file:

    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtQuick.Controls 1.4
      This program is for testing out OPC UA interfaces.
    Window {
        id: mainWindow
        visible: true
        width: 640
        height: 480
        title: qsTr("OPC UA Playground")
        signal operateSig()
        Connections {
            target: controller
            onStatus: {
        Button {
            id: operateButton
            text: "Operate"
            onClicked: {

    However, I get these errors:

    qrc:/main.qml:18:5: QML Connections: Cannot assign to non-existent property "onStatus"
    qrc:/main.qml:19: ReferenceError: controller is not defined

    I don't understand why it cannot see the "controller" object. I have set contexts before in other apps and it has worked. I have to be missing something really really simple.

  • Moderators

    @fcarney said in setContextProperty not setting context properly:

    QQmlContext *context = new QQmlContext(engine.rootContext());

    You are constructing a new context, which is not the same as the one your engine is running on.

    Do this instead:

    QQmlContext *context = engine.rootContext();
    context->setContextProperty("controller", &control);

    Or simpler:

    engine.rootContext()->setContextProperty("controller", &control);

    And then engine.load("qrc:/main.qml"); of course.

  • @sierdzio said in setContextProperty not setting context properly:

    You are constructing a new context, which is not the same as the one your engine is running on.

    Thank you! I got that from too much copy pasta trying to figure out how to do this. All my errors are gone now.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.