Qt Reference Documentation

Using QML in C++ Applications

The QML API is split into three main classes - QDeclarativeEngine, QDeclarativeComponent and QDeclarativeContext. QDeclarativeEngine provides the environment in which QML is run, QDeclarativeComponent encapsulates QML Documents, and QDeclarativeContext allows applications to expose data to QML component instances.

QML also includes a convenience API, QDeclarativeView, for applications that simply want to embed QML components into a new QGraphicsView. QDeclarativeView covers up many of the details discussed below. While QDeclarativeView is mainly intended for rapid prototyping it can have uses in production applications.

If you are looking at retrofitting an existing Qt application with QML, read Integrating QML with existing Qt UI code.

Basic Usage

Every application requires at least one QDeclarativeEngine. A QDeclarativeEngine allows the configuration of global settings that apply to all the QML component instances - such as the QNetworkAccessManager that is used for network communications, and the path used for persistent storage. Multiple QDeclarativeEngine's are only needed if the application requires these settings to differ between QML component instances.

QML Documents are loaded using the QDeclarativeComponent class. Each QDeclarativeComponent instance represents a single QML document. A QDeclarativeComponent can be passed a document URL, or raw text representing the content of the document. The document URL can be a local filesystem URL, or any network URL supported by QNetworkAccessManager.

QML component instances can then be created by calling the QDeclarativeComponent::create() method. Here's an example of loading a QML document, and creating an object from it.

 QDeclarativeEngine *engine = new QDeclarativeEngine(parent);
 QDeclarativeComponent component(engine, QUrl::fromLocalFile("main.qml"));
 QObject *myObject = component.create();

Exposing Data

QML components are instantiated in a QDeclarativeContext. A context allows the application to expose data to the QML component instance. A single QDeclarativeContext can be used to instantiate all the objects used by an application, or several QDeclarativeContext can be created for more fine grained control over the data exposed to each instance. If a context is not passed to the QDeclarativeComponent::create() method, the QDeclarativeEngine's root context is used. Data exposed through the root context is available to all object instances.

Simple Data

To expose data to a QML component instance, applications set context properties which are then accessible by name from QML Property Bindings and JavaScript. The following example shows how to expose a background color to a QML file through QDeclarativeView:

// main.cpp

 #include <QApplication>
 #include <QDeclarativeView>
 #include <QDeclarativeContext>

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

     QDeclarativeView view;
     QDeclarativeContext *context = view.rootContext();
     context->setContextProperty("backgroundColor",
                                 QColor(Qt::yellow));

     view.setSource(QUrl::fromLocalFile("main.qml"));
     view.show();

     return app.exec();
 }

// main.qml

 import Qt 4.7

 Rectangle {
     width: 300
     height: 300

     color: backgroundColor

     Text {
         anchors.centerIn: parent
         text: "Hello Yellow World!"
     }
 }

Or, if you want main.cpp to create the component without showing it in a QDeclarativeView, you could create an instance of QDeclarativeContext using QDeclarativeEngine::rootContext() instead:

     QDeclarativeEngine engine;
     QDeclarativeContext *windowContext = new QDeclarativeContext(engine.rootContext());
     windowContext->setContextProperty("backgroundColor", QColor(Qt::yellow));

     QDeclarativeComponent component(&engine, "main.qml");
     QObject *window = component.create(windowContext);

Context properties work just like normal properties in QML bindings - if the backgroundColor context property in this example was changed to red, the component object instances would all be automatically updated. Note that it is the responsibility of the creator to delete any QDeclarativeContext it constructs. If the windowContext is no longer needed when the window component instantiation is destroyed, the windowContext must be destroyed explicitly. The simplest way to ensure this is to set window as windowContext's parent.

QDeclarativeContexts form a tree - each QDeclarativeContext except for the root context has a parent. Child QDeclarativeContexts effectively inherit the context properties present in their parents. This gives applications more freedom in partitioning the data exposed to different QML object instances. If a QDeclarativeContext sets a context property that is also set in one of its parents, the new context property shadows that in the parent. In The following example, the background context property in Context 1 shadows the background context property in the root context.

Structured Data

Context properties can also be used to expose structured and writable data to QML objects. In addition to all the types already supported by QVariant, QObject derived types can be assigned to context properties. QObject context properties allow the data exposed to be more structured, and allow QML to set values.

The following example creates a CustomPalette object, and sets it as the palette context property.

 class CustomPalette : public QObject
 {
     Q_OBJECT
     Q_PROPERTY(QColor background READ background WRITE setBackground NOTIFY backgroundChanged)
     Q_PROPERTY(QColor text READ text WRITE setText NOTIFY textChanged)

 public:
     CustomPalette() : m_background(Qt::white), m_text(Qt::black) {}

     QColor background() const { return m_background; }
     void setBackground(const QColor &c) {
         if (c != m_background) {
             m_background = c;
             emit backgroundChanged();
         }
     }

     QColor text() const { return m_text; }
     void setText(const QColor &c) {
         if (c != m_text) {
             m_text = c;
             emit textChanged();
         }
     }

 signals:
     void textChanged();
     void backgroundChanged();

 private:
     QColor m_background;
     QColor m_text;
 };

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

     QDeclarativeView view;
     view.rootContext()->setContextProperty("palette", new CustomPalette);

     view.setSource(QUrl::fromLocalFile("main.qml"));
     view.show();

     return app.exec();
 }

The QML that follows references the palette object, and its properties, to set the appropriate background and text colors. When the window is clicked, the palette's text color is changed, and the window text will update accordingly.

 import Qt 4.7

 Rectangle {
     width: 240
     height: 320
     color: palette.background

     Text {
         anchors.centerIn: parent
         color: palette.text
         text: "Click me to change color!"
     }

     MouseArea {
         anchors.fill: parent
         onClicked: {
             palette.text = "blue";
         }
     }
 }

To detect when a C++ property value - in this case the CustomPalette's text property - changes, the property must have a corresponding NOTIFY signal. The NOTIFY signal specifies a signal that is emitted whenever the property changes value. Implementers should take care to only emit the signal if the value changes to prevent loops from occuring. Accessing a property from a binding that does not have a NOTIFY signal will cause QML to issue a warning at runtime.

Dynamic Structured Data

If an application is too dynamic to structure data as compile-time QObject types, dynamically structured data can be constructed at runtime using the QDeclarativePropertyMap class.

Calling C++ methods from QML

It is possible to call methods of QObject derived types by either exposing the methods as public slots, or by marking the methods Q_INVOKABLE.

The C++ methods can also have parameters and return values. QML has support for the following types:

This example toggles the "Stopwatch" object on/off when the MouseArea is clicked:

// main.cpp

 class Stopwatch : public QObject
 {
     Q_OBJECT
 public:
     Stopwatch();

     Q_INVOKABLE bool isRunning() const;

 public slots:
     void start();
     void stop();

 private:
     bool m_running;
 };

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

     QDeclarativeView view;
     view.rootContext()->setContextProperty("stopwatch",
                                            new Stopwatch);

     view.setSource(QUrl::fromLocalFile("main.qml"));
     view.show();

     return app.exec();
 }

// main.qml

 import Qt 4.7

 Rectangle {
     width: 300
     height: 300

     MouseArea {
         anchors.fill: parent
         onClicked: {
             if (stopwatch.isRunning())
                 stopwatch.stop()
             else
                 stopwatch.start();
         }
     }
 }

Note that in this particular example a better way to achieve the same result is to have a "running" property in main.qml. This leads to much nicer QML code:

 // main.qml
 import Qt 4.7

 Rectangle {
     MouseArea {
         anchors.fill: parent
         onClicked: stopwatch.running = !stopwatch.running
     }
 }

Of course, it is also possible to call functions declared in QML from C++.

Network Components

If the URL passed to QDeclarativeComponent is a network resource, or if the QML document references a network resource, the QDeclarativeComponent has to fetch the network data before it is able to create objects. In this case, the QDeclarativeComponent will have a Loading status. An application will have to wait until the component is Ready before calling QDeclarativeComponent::create().

The following example shows how to load a QML file from a network resource. After creating the QDeclarativeComponent, it tests whether the component is loading. If it is, it connects to the QDeclarativeComponent::statusChanged() signal and otherwise calls the continueLoading() method directly. This test is necessary, even for URLs that are known to be remote, just in case the component has been cached and is ready immediately.

 MyApplication::MyApplication()
 {
     // ...
     component = new QDeclarativeComponent(engine, QUrl("http://www.example.com/main.qml"));
     if (component->isLoading())
         QObject::connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)),
                          this, SLOT(continueLoading()));
     else
         continueLoading();
 }

 void MyApplication::continueLoading()
 {
     if (component->isError()) {
         qWarning() << component->errors();
     } else {
         QObject *myObject = component->create();
     }
 }

Qt Resources

QML content can be loaded from The Qt Resource System using the qrc: URL scheme. For example:

[project/example.qrc]

 <!DOCTYPE RCC>
 <RCC version="1.0">

 <qresource prefix="/">
     <file>main.qml</file>
     <file>images/background.png</file>
 </qresource>

 </RCC>

[project/project.pro]

 QT += declarative

 SOURCES += main.cpp
 RESOURCES += example.qrc

[project/main.cpp]

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

     QDeclarativeView view;
     view.setSource(QUrl("qrc:/main.qml"));
     view.show();

     return app.exec();
 }

[project/main.qml]

 import Qt 4.7

 Image {
     source: "images/background.png"
 }

Note that the resource system cannot be accessed from QML directly. If the main QML file is loaded as a resource, all files specifed as relative paths in QML will also be loaded from the resource system. Using the resource system is completely transparent to the QML layer. This also means that if the main QML file is not loaded as a resource then files in the resource system cannot be accessed from QML.

X

Thank you for giving your feedback.

Make sure it is related to this specific page. For more general bugs and requests, please use the Qt Bug Tracker.

[0]; s.parentNode.insertBefore(ga, s); })();