Important: Please read the Qt Code of Conduct -

Context property works in QQmlApplicationEngine but not in QQmlEngine.

  • Hello,
    Because I cannot save/load position of ApplicationWindow correctly, on X11 I have decided to use QMainWindow as base window application but I am stuck with context properties.
    Here you can see how I set the context properties in my main.cpp file.

    In the following is how I declared in QMainWindow constructor:

        QQuickWidget *view = new QQuickWidget();
        QQmlEngine *engine = view->engine();
        connect(engine, SIGNAL(quit()), this, SLOT(close()));
        QQmlContext *context = engine->rootContext();
        Util util;
        SettingsController settingsController;
        engine->addImageProvider(QLatin1String("customimage"), new CustomImageProvider());
        engine->addImageProvider(QLatin1String("fontimage"), new FontImageProvider());
        context->setContextProperty("util", &util);
        context->setContextProperty("settingsController", &settingsController);
        context->setContextProperty("applicationPath", "file://" + qApp->applicationDirPath() + "/");
        if (Util::osType() == "android")
        if (QFile::exists(QApplication::applicationDirPath() + "/maintenancetool")) {
            QThread thread;
            ThreadWorker *threadWorker = new ThreadWorker();
            QObject::connect(&thread, SIGNAL(finished()), threadWorker, SLOT(deleteLater()));
            QObject::connect(threadWorker, SIGNAL(updateSearchFinished()), &thread, SLOT(quit()));

    My issue is that when I call method of object declared as context property("util" in my example) I get TypeError: Cannot call method '<any-method-here>' of null, while "applicationPath" property works correctly.

    Methods are marked as Q_INVOKABLE.

    Any ideeas on what am I doing wrong?

  • Qt Champions 2017

    U r creating stack objects in constructor. All these objects are destroyed once the constructor is over. Create dynamic object & things should work.

  • @adutzu89
    @dheerendra is correct. The string works because it's not a pointer or reference but is copied and becomes a javascript string by automatic C++/QML type conversion. However, I don't know what dheerendra means by "dynamic", maybe that they can be heap objects; you can have the objects also as direct members of your main window class without pointers and new. That would be better modern C++ style unless you need to reach the parent main window object from your objects.

  • @dheerendra and @Eeli-K thank you for your answers it helped :).

    @Eeli-K he reffers to instantiate the object with the "new" operator.
    In my constructor, as an example:

    Util *util = new Util();

    works correctly.

Log in to reply