qml Integration with C++ Creating a QtQuick Window from C++


As of Qt 5.1 and later you can use QQmlApplicationEngine instead of QQuickView to load and render a QML script.

With QQmlApplicationEngine you do need to use a QML Window type as your root element.

You can obtain the root context from the engine where you can then add global properties to the context which can be access by the engine when processing QML scripts.


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    QQmlContext* rootContext = engine.rootContext();
    rootContext->setContextProperty("WINDOW_WIDTH", 640);
    rootContext->setContextProperty("WINDOW_HEIGHT", 360);


    return app.exec();


import QtQuick 2.5
import QtQuick.Window 2.2

Window { // Must be this type to be loaded by QQmlApplicationEngine.
    visible: true
    width: WINDOW_WIDTH   //Accessing global context declared in C++
    height: WINDOW_HEIGHT //Accessing global context declared in C++
    title: qsTr("Hello World")
    Component.onCompleted: {
        // We can access global context from within JavaScript too.
        console.debug( "Width: " + WINDOW_WIDTH )
        console.debug( "Height: " + WINDOW_HEIGHT )

    MouseArea {
        anchors.fill: parent
        onClicked: {

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent