CPP QML Singleton registered with qmlRegisterSingletonType fails to load
-
I'm trying to register a QObject as QML singleton via cpp.
The singleton is located in a shared library not in the main application.My Object looks something like this:
// header class SHARED_EXPORT Singleton : public QObject { Q_OBJECT public: explicit Singleton(QObject *parent = nullptr); void method1(const QString &message); static Singleton *globalInstance(); signals: // some signals public slots: // some slots }; // source Q_GLOBAL_STATIC(Singleton, theInstance) Singleton * Singleton::globalInstance() { return theInstance; }
The singleton provider is located in another header
namespace QMLSingleton { static QObject *globalInstance(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) QObject *instance = Singleton::globalInstance(); QQmlEngine::setObjectOwnership(instance, QQmlEngine::CppOwnership); return instance; } }
I register the singleton in main via:
qmlRegisterSingletonType<Singleton>("Package", 1, 0, "Singleton", QMLSingleton::globalInstance);
everything compiles fine and qmlRegisterSingletonType works without any errors.
I also have auto completion in the qml editor showing all signals / slots of the registered singleton.
But once I load the main.qml file of the app this errors shows up
QQmlApplicationEngine failed to load component qrc:/main.qml:29 Non-existent attached object // in line 29 I am using the registered singleton
I also tried less complex examples (like this one https://stackoverflow.com/a/26782682)
but even if I declare a really simple qobject and provider in the shared lib or directly in the main application and register it I get the same error.Any ideas whats causing this issue?
EDIT:
I also tried to create the singleton without a singleton factory (Q_GLOBAL_STATIC)
namespace QMLSingleton { static QObject *globalInstance(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return new Singleton(); } }
... same result