Important: Please read the Qt Code of Conduct -

QML exposed objects across shared library boundaries

  • Moderators


    Say I have an application where I add some QML files to a module (through the generated template):

        URI MyNamespace
        VERSION MyVersion

    Is it possible for me to inject into this namespace a (QML) singleton object from a shared library?

    What I have currently in the application code for testing is:

    int main(int argc, char ** argv)
        MySingletonClass singleton;
        QQmlApplicationEngine engine;
        // ... init code for engine
        qmlRegisterSingletonInstance("MyNamespace", 0, 1, "MySingletonClassName", &singleton);
        // ...
        return app.exec();

    Is this the right way to do it?
    Must I also add the QML_ELEMENT and QML_SINGLETON macros to the MySingletonClass, or if I don't use a QML module in the library I can skip this?

  • Moderators

    Well, I forgot about this a little bit, but I'm adding the solution anyway for future reference.

    After some reading through the documentation and experimenting, it appears that dynamically registering a foreign class to a qml module declared as above isn't possible (nor encouraged, nor supported, as per the docs). The "old" way of plugin whatever you want into the registered QML namespace doesn't work anymore.

    The proper solution is to wrap the class as described in the docs and use that wrapper to expose it to the QML engine. Like follows (Tsc::Engine is what I'm attempting to inject):


    #include <QQmlEngine>
    #include <QJSEngine>
    struct EngineForeign
        static Tsc::Engine * create(QQmlEngine *, QJSEngine *);
        static QJSEngine * currentJsEngine;


    #include "TscQml.h"
    QJSEngine * EngineForeign::currentJsEngine = nullptr;
    Tsc::Engine * EngineForeign::create(QQmlEngine *, QJSEngine * jsEngine)
        Tsc::Engine * engine = Tsc::Engine::instance();
        Q_ASSERT(engine->thread() == jsEngine->thread());
        Q_ASSERT(!currentJsEngine || currentJsEngine == jsEngine);
        currentJsEngine = jsEngine;
        QJSEngine::setObjectOwnership(engine, QJSEngine::CppOwnership);
        return engine;
    #include "moc_TscQml.cpp"

    After that everything works as expected and I can see and use it in QML:

    import QtQuick
    import QtQuick.Controls
    import Tsc
    ApplicationWindow {
        width: 640
        height: 480
        visible: true
        title: qsTr("Hello World")
        Rectangle {
            anchors.fill: parent
            color: 'red'
            Connections {
                target: Engine.simulation
                function onAdvanced() {

    Notably, this must be done for the singleton itself only. simulation is a QObject and a registered property (Q_PROPERTY) of the Tsc::Engine instance, which hasn't been wrapped nor does it appear necessary for this class to be exposed explicitly to the QML engine.

Log in to reply