Keep created object alive. How?
-
Hello all!
I am running static function from one class that should create some objects and attach it to main function. How to do it in Qt?main.cpp
int main(int Counter, char *Arguments[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); CustomApplication Application(Counter,Arguments); QQmlApplicationEngine Engine; >>>> CustomClass::staticFunction(&Engine) Engine.load(QUrl(Main)); if (Engine.rootObjects().isEmpty()) return -1; return Application.exec();
customclass.cpp
void CustomClass::staticFunction(QQmlApplicationEngine &Engine) { QQmlContext *Context = Engine.rootContext(); Settings appSettings; Context->setContextProperty("Settings",&appSettings); }
In this example object appSettings should be alive in main function scope after finishing of execution of this static function. Beside this the list of objects might be bigger.
-
Allocate on the heap and give ownership of the memory to something else (
Engine
?)Settings* appSettings = new Settings; QObject::connect(&Engine,&QObject::destroyed,[appSettings](){delete appSettings;}); Context->setContextProperty("Settings",appSettings);
-
Or simply let Settings derive from QObject and pass Engine as parent so it will automatically destroyed when Engine is deleted.
-
@VRonin Engine is object that is conaining context. I need to hold Settings standalone in main, but be contexted to Engine. Global idea - create standalone objects from static function, keep them alive when function finished and hold them in context of Engine.
Thanks for reply. I am always trying to avoid HEAP. In this case it's might be better to use kind of object-wrapper and in constructor of it do everything I need and keep it alive in main by direct implementation.
-
@Christian-Ehrlicher Will try to do it in hour. But the global idea was to develop them like standalone object but inside of main.
-
Decided do not making additional complexity. The solution is - do not do anything additional and use plain objects definition inside of "main" function.
Qt Project example published in Github
main.cpp
int main(int Counter, char *Arguments[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); CuxtomApplication Application(Counter,Arguments); QQmlApplicationEngine Engine; QQmlContext *Context = Engine.rootContext(); AppSettings Settings; Context->setContextProperty("Settings",&Settings); Engine.load(QUrl(Main)); if (Engine.rootObjects().isEmpty()) return -1; return Application.exec(); }