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++ source 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 specific file types (shown in the middle), then click Choose...
  3. In the Location page, 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;
        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 file for editing and add the following 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.
  7. Build the project by accessing the Build menu and clicking Build Project "QtApp".