Adding code to load the UI

The QML file defines how the UI looks but to display it when the Qt app starts, your app must contain C++ code that defines the application entry point and loads the UI.

To add code that loads the UI:
  1. In the Project view, right-click the QtApp folder and click Add New...
  2. In the New File dialog, select C++ in the Files and Classes list, then C++ Source file in the list of file types (shown in the middle), then click Choose...
  3. In the Location page in the resulting dialog, name the file main, then click Next.
  4. In the Summary page, click Finish.

    The main.cpp file is opened for editing.

  5. Copy and paste the following code into main.cpp:
    #include <QtGui/QGuiApplication>
    #include <QtQuick/QQuickView>
    
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
    
        QQuickView view;
        view.setSource(QUrl("qrc:/ui/main.qml"));
        view.show();
    
        return app.exec();
    }
    
    In this code, the view loads the main.qml resource from the Qt resource file, and then displays the UI. Note the syntax for accessing resources in a .qrc file, which consists of the resource path prepended with qrc:. So, to access main.qml, the view uses qrc:/ui/main.qml (because the prefix was defined as ui).
  6. Open the project file (QtApp.pro) for editing and add this line at the end:
    QT += quick
    
    Because main.cpp includes the QtQuick/QQuickView header file, you must tell Qt Creator to use the quick package.
    Note: The project file can define many variables that affect how qmake builds the project; for the full list, see the Variables | QMake reference in Digia's online Qt documentation.