Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

What is the difference between main.cpp templates?



  • Hello!
    Just got noticed that there are difference in previous templates for Qt Quick application in templates:

    • Now in Qt Creator distribution this:
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    int main(int argc, char *argv[])
    {
    	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
    	QGuiApplication app(argc, argv);
    
    	QQmlApplicationEngine engine;
    	const QUrl url(QStringLiteral("qrc:/main.qml"));
    	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
    					 &app, [url](QObject *obj, const QUrl &objUrl) {
    		if (!obj && url == objUrl)
    			QCoreApplication::exit(-1);
    	}, Qt::QueuedConnection);
    	engine.load(url);
    
    	return app.exec();
    }
    
    • Before was this:
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    const QString Main = "qrc:/main.qml";
    
    int main(int Counter, char *Arguments[]) {
    
    	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    	QGuiApplication Application(Counter, Arguments);
    
    	QQmlApplicationEngine Engine;
    	Engine.load(QUrl(Main));
    	if (Engine.rootObjects().isEmpty())
    		return -1;
    
    	return Application.exec();
    }
    

    What is the difference? What is better to use? Should I rewrite previous applications?


  • Moderators

    I don't know much about QML but apart from some formatting, variable name changing and getting rid of a global variable (which is nice), the main difference seems to be the initial check for root object.
    Previous code assumes it is already available right after calling load(). The new one waits for a signal from the engine.

    Again, I don't know inner workings of QML engine, but if creation of the root object can be deferred in some cases to some later frames in the event loop, the previous code would do the check too early and close the app, while the new one properly waits for the engine to tell it when it's ok to check.
    The other possible issue is if you inject some other root objects of your own. In that case, if the main.qml fails to load that previous check wouldn't detect that, while the new one checks for that specific object.

    Should you rewrite your apps? If you experience "sometimes the app doesn't start" or "sometimes it crashes on startup" type of issues this might be the cause, otherwise it shouldn't matter as it's just a one time check for main content on init.



  • @Chris-Kawa Thx a lot ... Got the list of key-words for research about Qt techniques. Issue closed.


Log in to reply