Tests crash when using C++ Singletons
-
Hello,
I have two QML components that use same singleton object and I'm trying to test them. Singleton is registered viaqmlRegisterSingletonType()
inmain.cpp
. Each test file separately works fine, but the tests crashes when I run both tests. After some digging I found out thatcleanUpTestcase()
from first test deletes the singleton and crash happens when second component calls the singleton object.
I also found very similar problem reported as bug here, but the workaround suggested by assignee doesn't work for me. When registered, singleton always logs that it has CppOwnership:QObject* SingletonObject::register(QQmlEngine *engine, QJSEngine *scriptEngine) { static SingletonObject* self = new SingletonObject(); qDebug()<<"[SingletonObject]"<<(engine->objectOwnership(self) ? "JsOwnership" : "CppOwnership"); return self; }
Which means
QQmlEngine::setObjectOwnership(instance, QQmlEngine::CppOwnership);
will do nothing in my case.
Is there any other option to avoid this crash? -
@PavloPonomarov said in Tests crash when using C++ Singletons:
When registered, singleton always logs that it has CppOwnership
at this moment in time?, yes true, as soon as the function actually returns and the pointer is passed to the QMLEngine, the object ownership changes.
That also means, you'll have to set ownership after the QMLEngine has taken over.
the hacky way I do/did this is/was:
static QObject *instance(QQmlEngine *engine, QJSEngine *) { ClimateSetting = new ClimateSettings(); QMetaObject::invokeMethod(ClimateSetting, [=]()->void{ engine->setObjectOwnership(ClimateSetting, QQmlEngine::CppOwnership); }, Qt::QueuedConnection); return ClimateSetting; }
-
@J-Hilk said in Tests crash when using C++ Singletons:
QMetaObject::invokeMethod(ClimateSetting, =->void{
engine->setObjectOwnership(ClimateSetting, QQmlEngine::CppOwnership);
}, Qt::QueuedConnection);If I am reading the docs right, this looks like a way to do a callLater on the object. Did not know you could do that from C++. Thanks for sharing.
-
@PavloPonomarov said in Tests crash when using C++ Singletons:
When registered, singleton always logs that it has CppOwnership:
Which means QQmlEngine::setObjectOwnership(instance, QQmlEngine::CppOwnership); will do nothing in my case.Not really, CppOwnership is also returned for objects with no explicit ownership. If you were to set it explicitely, it won't be overwritten later by the engine.