Using QML Bindings in C++ Applications

QML is designed to be easily extensible to and from C++. The classes in the Qt Declarative module allow QML components to be loaded and manipulated from C++, and through Qt's meta-object system, QML and C++ objects can easily communicate through Qt signals and slots. In addition, QML plugins can be written to create reusable QML components for distribution.

You may want to mix QML and C++ for a number of reasons. For example:

  • To use functionality defined in a C++ source (for example, when using a C++ Qt-based data model, or calling functions in a third-party C++ library)
  • To access functionality in the Qt Declarative module (for example, to dynamically generate images using QDeclarativeImageProvider)
  • To write your own QML elements (whether for your applications, or for distribution to others)

To use the Qt Declarative module, you must include and link to the module appropriately, as shown on the module index page. The Qt Declarative UI Runtime documentation shows how to build a basic C++ application that uses this module.

Core module classes

The Qt Declarative module provides a set of C++ APIs for extending your QML applications from C++ and embedding QML into C++ applications. There are several core classes in the Qt Declarative module that provide the essential capabilities for doing this. These are:

A QDeclarativeEngine allows the configuration of global settings that apply to all of its QML component instances: for example, the QNetworkAccessManager to be used for network communications, and the file path to be used for persistent storage.

QDeclarativeComponent is used to load QML documents. Each QDeclarativeComponent instance represents a single document. A component can be created from the URL or file path of a QML document, or the raw QML code of the document. Component instances are instatiated through the QDeclarativeComponent::create() method, like this:

  1.                 QDeclarativeEngine engine;
  2. QDeclarativeComponent component(&engine, QUrl::fromLocalFile("MyRectangle.qml"));
  3. QObject *rectangleInstance = component.create();
  4.  
  5. // ...
  6. delete rectangleInstance;

QML documents can also be loaded using QDeclarativeView. This class provides a convenient QWidget-based view for embedding QML components into QGraphicsView-based applications. (For other methods of integrating QML into QWidget-based applications, see Integrating QML Code with existing Qt UI code.)

Approaches to using QML with C++

There are a number of ways to extend your QML application through C++. For example, you could:

  • Load a QML component and manipulate it (or its children) from C++
  • Embed a C++ object and its properties directly into a QML component (for example, to make a particular C++ object callable from QML, or to replace a dummy list model with a real data set)
  • Define new QML elements (through QObject-based C++ classes) and create them directly from your QML code

These methods are shown below. Naturally these approaches are not exclusive; you can mix any of these methods throughout your application as appropriate.

Loading QML components from C++

A QML document can be loaded with QDeclarativeComponent or QDeclarativeView. QDeclarativeComponent loads a QML component as a C++ object; QDeclarativeView also does this, but additionally loads the QML component directly into a QGraphicsView. It is convenient for loading a displayable QML component into a QWidget-based application.

For example, suppose there is a MyItem.qml file that looks like this:

  1. import QtQuick 1.0
  2.  
  3. Item  {
  4.     width: 100; height: 100
  5. }

This QML document can be loaded with QDeclarativeComponent or QDeclarativeView with the following C++ code. Using a QDeclarativeComponent requires calling QDeclarativeComponent::create() to create a new instance of the component, while a QDeclarativeView automatically creates an instance of the component, which is accessible via QDeclarativeView::rootObject():

  1. // Using QDeclarativeComponent
  2. QDeclarativeEngine engine;
  3. QDeclarativeComponent component(&engine,
  4.         QUrl::fromLocalFile("MyItem.qml"));
  5. QObject *object = component.create();
  6. ...
  7. delete object;
  1. // Using QDeclarativeView
  2. QDeclarativeView view;
  3. view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  4. view.show();
  5. QObject *object = view.rootObject();

This object is the instance of the MyItem.qml component that has been created. You can now modify the item's properties using QObject::setProperty() or QDeclarativeProperty:

  1. object->setProperty("width", 500);
  2. QDeclarativeProperty(object, "width").write(500);

Alternatively, you can cast the object to its actual type and call functions with compile-time safety. In this case the base object of MyItem.qml is an Item, which is defined by the QDeclarativeItem class:

  1.                 QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(object);
  2. item->setWidth(500);

You can also connect to any signals or call functions defined in the component using QMetaObject::invokeMethod() and QObject::connect(). See Exchanging data between QML and C++ below for further details.

Locating child objects

QML components are essentially object trees with children that have siblings and their own children. Child objects of QML components can be located using the QObject::objectName property with QObject::findChild(). For example, if the root item in MyItem.qml had a child Rectangle item:

  1. import QtQuick 1.0
  2.  
  3. Item  {
  4.     width: 100; height: 100
  5.  
  6.     Rectangle  {
  7.         anchors.fill: parent
  8.         objectName: "rect"
  9.     }
  10. }

The child could be located like this:

  1.                 QObject *rect = object->findChild<QObject*>("rect");
  2. if (rect)
  3.     rect->setProperty("color", "red");

If objectName is used inside a delegate of a ListView, Repeater or some other element that creates multiple instances of its delegates, there will be multiple children with the same objectName. In this case, QObject::findChildren() can be used to find all children with a matching objectName.

Warning: While it is possible to use C++ to access and manipulate QML objects deep into the object tree, we recommend that you do not take this approach outside of application testing and prototyping. One strength of QML and C++ integration is the ability to implement the QML user interface separately from the C++ logic and dataset backend, and this strategy breaks if the C++ side reaches deep into the QML components to manipulate them directly. This would make it difficult to, for example, swap a QML view component for another view, if the new component was missing a required objectName. It is better for the C++ implementation to know as little as possible about the QML user interface implementation and the composition of the QML object tree.

Embedding C++ objects into QML components

When loading a QML scene into a C++ application, it can be useful to directly embed C++ data into the QML object. QDeclarativeContext enables this by exposing data to the context of a QML component, allowing data to be injected from C++ into QML.

For example, here is a QML item that refers to a currentDateTime value that does not exist in the current scope:

  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Text  { text: currentDateTime }

This currentDateTime value can be set directly by the C++ application that loads the QML component, using QDeclarativeContext::setContextProperty():

  1.                 QDeclarativeView view;
  2. view.rootContext()->setContextProperty("currentDateTime", QDateTime::currentDateTime());
  3. view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  4. view.show();

Context properties can hold either QVariant or QObject* values. This means custom C++ objects can also be injected using this approach, and these objects can be modified and read directly in QML. Here, we modify the above example to embed a QObject instance instead of a QDateTime value, and the QML code invokes a method on the object instance:

  1. class ApplicationData : public QObject
  2.  {
  3.     Q_OBJECT
  4. public:
  5.     Q_INVOKABLE QDateTime getCurrentDateTime() const  {
  6.         return QDateTime::currentDateTime();
  7.     }
  8. };
  9.  
  10. int main(int argc, char *argv[])  {
  11.     QApplication app(argc, argv);
  12.  
  13.     QDeclarativeView view;
  14.  
  15.     ApplicationData data;
  16.     view.rootContext()->setContextProperty("applicationData", &data);
  17.  
  18.     view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  19.     view.show();
  20.  
  21.     return app.exec();
  22. }
  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Text  { text: applicationData.getCurrentDateTime() }

(Note that date/time values returned from C++ to QML can be formatted through Qt.formatDateTime() and associated functions.)

If the QML item needs to receive signals from the context property, it can connect to them using the Connections element. For example, if ApplicationData has a signal named dataChanged(), this signal can be connected to using an onDataChanged handler within a Connections object:

  1.                 Text  {
  2.     text: applicationData.getCurrentDateTime()
  3.  
  4.     Connections  {
  5.         target: applicationData
  6.         onDataChanged: console.log("The application data changed!")
  7.     }
  8. }

Context properties can be useful for using C++ based data models in a QML view. See the String ListModel, Object ListModel and AbstractItemModel models for respective examples on using QStringListModel, QObjectList-based models and QAbstractItemModel in QML views.

Also see the QDeclarativeContext documentation for more information.

Defining new QML elements

While new QML elements can be defined in QML, they can also be defined by C++ classes; in fact, many of the core QML Elements are implemented through C++ classes. When you create a QML object using one of these elements, you are simply creating an instance of a QObject-based C++ class and setting its properties.

To create a visual item that fits in with the Qt Quick elements, base your class off QDeclarativeItem instead of QObject directly. You can then implement your own painting and functionality like any other QGraphicsObject. Note that QGraphicsItem::ItemHasNoContents is set by default on QDeclarativeItem because it does not paint anything; you will need to clear this if your item is supposed to paint anything (as opposed to being solely for input handling or logical grouping).

For example, here is an ImageViewer class with an image URL property:

  1. #include <QtCore>
  2. #include <QtDeclarative>
  3.  
  4. class ImageViewer : public QDeclarativeItem
  5.  {
  6.     Q_OBJECT
  7.     Q_PROPERTY(QUrl image READ image WRITE setImage NOTIFY imageChanged)
  8.  
  9. public:
  10.     void setImage(const QUrl &url);
  11.     QUrl image() const;
  12.  
  13. signals:
  14.     void imageChanged();
  15. };

Aside from the fact that it inherits QDeclarativeItem, this is an ordinary class that could exist outside of QML. However, once it is registered with the QML engine using qmlRegisterType():

  1. qmlRegisterType<ImageViewer>("MyLibrary", 1, 0, "ImageViewer");

Then, any QML code loaded by your C++ application or plugin can create and manipulate ImageViewer objects:

  1. import MyLibrary 1.0
  2.  
  3. ImageViewer  { image: "smile.png" }

It is advised that you avoid using QGraphicsItem functionality beyond the properties documented in QDeclarativeItem. This is because the GraphicsView backend is intended to be an implementation detail for QML, so the QtQuick items can be moved to faster backends as they become available with no change from a QML perspective. To minimize any porting requirements for custom visual items, try to stick to the documented properties in QDeclarativeItem where possible. Properties QDeclarativeItem inherits but doesn't document are classed as implementation details; they are not officially supported and may disappear between releases.

Note that custom C++ types do not have to inherit from QDeclarativeItem; this is only necessary if it is a displayable item. If the item is not displayable, it can simply inherit from QObject.

For more information on defining new QML elements, see the Writing QML extensions with C++ tutorial and the Extending QML Functionalities using C++ reference documentation.

Exchanging data between QML and C++

QML and C++ objects can communicate with one another through signals, slots and property modifications. For a C++ object, any data that is exposed to Qt's Meta-Object System - that is, properties, signals, slots and Q_INVOKABLE methods - become available to QML. On the QML side, all QML object data is automatically made available to the meta-object system and can be accessed from C++.

Calling functions

QML functions can be called from C++ and vice-versa.

All QML functions are exposed to the meta-object system and can be called using QMetaObject::invokeMethod(). Here is a C++ application that uses this to call a QML function:

  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Item  {
  5.     function myQmlFunction(msg)  {
  6.         console.log("Got message:", msg)
  7.         return "some return value"
  8.     }
  9. }
  1. // main.cpp
  2. QDeclarativeEngine engine;
  3. QDeclarativeComponent component(&engine, "MyItem.qml");
  4. QObject *object = component.create();
  5.  
  6. QVariant returnedValue;
  7. QVariant msg = "Hello from C++";
  8. QMetaObject::invokeMethod(object, "myQmlFunction",
  9.         Q_RETURN_ARG(QVariant, returnedValue),
  10.         Q_ARG(QVariant, msg));
  11.  
  12. qDebug() << "QML function returned:" << returnedValue.toString();
  13. delete object;

Notice the Q_RETURN_ARG() and Q_ARG() arguments for QMetaObject::invokeMethod() must be specified as QVariant types, as this is the generic data type used for QML functions and return values.

To call a C++ function from QML, the function must be either a Qt slot, or a function marked with the Q_INVOKABLE macro, to be available to QML. In the following example, the QML code invokes methods on the myObject object, which has been set using QDeclarativeContext::setContextProperty():

  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Item  {
  5.     width: 100; height: 100
  6.  
  7.     MouseArea  {
  8.         anchors.fill: parent
  9.         onClicked:  {
  10.             myObject.cppMethod("Hello from QML")
  11.             myObject.cppSlot(12345)
  12.         }
  13.     }
  14. }
  1. class MyClass : public QObject
  2.  {
  3.     Q_OBJECT
  4. public:
  5.     Q_INVOKABLE void cppMethod(const QString &msg)  {
  6.         qDebug() << "Called the C++ method with" << msg;
  7.     }
  8.  
  9. public slots:
  10.     void cppSlot(int number)  {
  11.         qDebug() << "Called the C++ slot with" << number;
  12.     }
  13. };
  14.  
  15. int main(int argc, char *argv[])  {
  16.     QApplication app(argc, argv);
  17.  
  18.     QDeclarativeView view;
  19.     MyClass myClass;
  20.     view.rootContext()->setContextProperty("myObject", &myClass);
  21.  
  22.     view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  23.     view.show();
  24.  
  25.     return app.exec();
  26. }

QML supports the calling of overloaded C++ functions. If there are multiple C++ functions with the same name but different arguments, the correct function will be called according to the number and the types of arguments that are provided.

Receiving signals

All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal. In return, any C++ signal can be received by a QML object using signal handlers.

Here is a QML component with a signal named qmlSignal. This signal is connected to a C++ object's slot using QObject::connect(), so that the cppSlot() method is called whenever the qmlSignal is emitted:

  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Item  {
  5.     id: item
  6.     width: 100; height: 100
  7.  
  8.     signal qmlSignal(string msg)
  9.  
  10.     MouseArea  {
  11.         anchors.fill: parent
  12.         onClicked: item.qmlSignal("Hello from QML")
  13.     }
  14. }
  1. class MyClass : public QObject
  2.  {
  3.     Q_OBJECT
  4. public slots:
  5.     void cppSlot(const QString &msg)  {
  6.         qDebug() << "Called the C++ slot with message:" << msg;
  7.     }
  8. };
  9.  
  10. int main(int argc, char *argv[])  {
  11.     QApplication app(argc, argv);
  12.  
  13.     QDeclarativeView view(QUrl::fromLocalFile("MyItem.qml"));
  14.     QObject *item = view.rootObject();
  15.  
  16.     MyClass myClass;
  17.     QObject::connect(item, SIGNAL(qmlSignal(QString)),
  18.                      &myClass, SLOT(cppSlot(QString)));
  19.  
  20.     view.show();
  21.     return app.exec();
  22. }

To connect to Qt C++ signals from within QML, use a signal handler with the on<SignalName> syntax. If the C++ object is directly creatable from within QML (see Defining new QML elements above) then the signal handler can be defined within the object declaration. In the following example, the QML code creates a ImageViewer object, and the imageChanged and loadingError signals of the C++ object are connected to through onImagedChanged and onLoadingError signal handlers in QML:

  1. class ImageViewer : public QDeclarativeItem
  2.  {
  3.     Q_OBJECT
  4.     Q_PROPERTY(QUrl image READ image WRITE setImage NOTIFY imageChanged)
  5. public:
  6.     ...
  7. signals:
  8.     void imageChanged();
  9.     void loadingError(const QString &errorMsg);
  10. };
  1. ImageViewer  {
  2.     onImageChanged: console.log("Image changed!")
  3.     onLoadingError: console.log("Image failed to load:", errorMsg)
  4. }

(Note that if a signal has been declared as the NOTIFY signal for a property, QML allows it to be received with an on<Property>Changed handler even if the signal's name does not follow the <Property>Changed naming convention. In the above example, if the "imageChanged" signal was named "imageModified" instead, the onImageChanged signal handler would still be called.)

If, however, the object with the signal is not created from within the QML code, and the QML item only has a reference to the created object - for example, if the object was set using QDeclarativeContext::setContextProperty() - then the Connections element can be used instead to create the signal handler:

  1. ImageViewer viewer;
  2.  
  3. QDeclarativeView view;
  4. view.rootContext()->setContextProperty("imageViewer", &viewer);
  5.  
  6. view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  7. view.show();
  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Item  {
  5.     Connections  {
  6.         target: imageViewer
  7.         onImageChanged: console.log("Image has changed!")
  8.     }
  9. }

C++ signals can use enum values as parameters provided that the enum is declared in the class that is emitting the signal, and that the enum is registered using Q_ENUMS. See Using enumerations of a custom type below for details.

Modifying properties

Any properties declared in a QML object are automatically accessible from C++. Given a QML item like this:

  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Item  {
  5.     property int someNumber: 100
  6. }

The value of the someNumber property can be set and read using QDeclarativeProperty, or QObject::setProperty() and QObject::property():

  1.                 QDeclarativeEngine engine;
  2. QDeclarativeComponent component(&engine, "MyItem.qml");
  3. QObject *object = component.create();
  4.  
  5. qDebug() << "Property value:" << QDeclarativeProperty::read(object, "someNumber").toInt();
  6. QDeclarativeProperty::write(object, "someNumber", 5000);
  7.  
  8. qDebug() << "Property value:" << object->property("someNumber").toInt();
  9. object->setProperty("someNumber", 100);

You should always use QObject::setProperty(), QDeclarativeProperty or QMetaProperty::write() to change a QML property value, to ensure the QML engine is made aware of the property change. For example, say you have a custom element PushButton with a buttonText property that internally reflects the value of a m_buttonText member variable. Modifying the member variable directly like this is not a good idea:

  1. // BAD!
  2. QDeclarativeComponent component(engine, "MyButton.qml");
  3. PushButton *button = qobject_cast<PushButton*>(component.create());
  4. button->m_buttonText = "Click me";

Since the value is changed directly, this bypasses Qt's meta-object system and the QML engine is not made aware of the property change. This means property bindings to buttonText would not be updated, and any onButtonTextChanged handlers would not be called.

Any Qt properties - that is, those declared with the Q_PROPERTY() macro - are accessible from QML. Here is a modified version of the earlier example on this page; here, the ApplicationData class has a backgroundColor property. This property can be written to and read from QML:

  1. class ApplicationData : public QObject
  2.  {
  3.     Q_OBJECT
  4.     Q_PROPERTY(QColor backgroundColor
  5.             READ backgroundColor
  6.             WRITE setBackgroundColor
  7.             NOTIFY backgroundColorChanged)
  8.  
  9. public:
  10.     void setBackgroundColor(const QColor &c)  {
  11.         if (c != m_color)  {
  12.             m_color = c;
  13.             emit backgroundColorChanged();
  14.         }
  15.     }
  16.  
  17.     QColor backgroundColor() const  {
  18.         return m_color;
  19.     }
  20.  
  21. signals:
  22.     void backgroundColorChanged();
  23.  
  24. private:
  25.     QColor m_color;
  26. };
  1. // MyItem.qml
  2. import QtQuick 1.0
  3.  
  4. Rectangle  {
  5.     width: 100; height: 100
  6.     color: applicationData.backgroundColor
  7.  
  8.     MouseArea  {
  9.         anchors.fill: parent
  10.         onClicked: applicationData.backgroundColor = "red"
  11.     }
  12. }

Notice the backgroundColorChanged signal is declared as the NOTIFY signal for the backgroundColor property. If a Qt property does not have an associated NOTIFY signal, the property cannot be used for Property Binding in QML, as the QML engine would not be notified when the value changes. If you are using custom types in QML, make sure their properties have NOTIFY signals so that they can be used in property bindings.

See Tutorial: Writing QML extensions with C++ for further details and examples on using Qt properties with QML.

Supported data types

Any C++ data that is used from QML - whether as custom properties, or parameters for signals or functions - must be of a type that is recognizable by QML.

By default, QML recognizes the following data types:

To allow a custom C++ type to be created or used in QML, the C++ class must be registered as a QML type using qmlRegisterType(), as shown in the Defining new QML elements section above.

JavaScript arrays and objects

There is built-in support for automatic type conversion between QVariantList and JavaScript arrays, and QVariantMap and JavaScript objects.

For example, the function defined in QML below left expects two arguments, an array and an object, and prints their contents using the standard JavaScript syntax for array and object item access. The C++ code below right calls this function, passing a QVariantList and a QVariantMap, which are automatically converted to JavaScript array and object values, repectively:

  1. // MyItem.qml
  2. Item  {
  3.     function readValues(anArray, anObject)  {
  4.         for (var i=0; i<anArray.length; i++)
  5.             console.log("Array item:", anArray[i])
  6.  
  7.         for (var prop in anObject)  {
  8.             console.log("Object item:", prop, "=", anObject[prop])
  9.         }
  10.     }
  11. }
  1. // C++
  2. QDeclarativeView view(QUrl::fromLocalFile("MyItem.qml"));
  3.  
  4. list << 10 << Qt::green << "bottles";
  5.  
  6. map.insert("language", "QML");
  7. map.insert("released", QDate(2010, 9, 21));
  8.  
  9. QMetaObject::invokeMethod(view.rootObject(), "readValues",
  10.         Q_ARG(QVariant, QVariant::fromValue(list)),
  11.         Q_ARG(QVariant, QVariant::fromValue(map)));

This produces output like:

  1. Array item: 10
  2. Array item: #00ff00
  3. Array item: bottles
  4. Object item: language = QML
  5. Object item: released = Tue Sep 21 2010 00:00:00 GMT+1000 (EST)

Similarly, if a C++ type uses a QVariantList or QVariantMap type for a property or method parameter, the value can be created as a JavaScript array or object in the QML side, and is automatically converted to a QVariantList or QVariantMap when it is passed to C++.

Using enumerations of a custom type

To use an enumeration from a custom C++ component, the enumeration must be declared with Q_ENUMS() to register it with Qt's meta object system. For example, the following C++ type has a Status enum:

  1. class ImageViewer : public QDeclarativeItem
  2.  {
  3.     Q_OBJECT
  4.     Q_ENUMS(Status)
  5.     Q_PROPERTY(Status status READ status NOTIFY statusChanged)
  6. public:
  7.     enum Status  {
  8.         Ready,
  9.         Loading,
  10.         Error
  11.     };
  12.  
  13.     Status status() const;
  14. signals:
  15.     void statusChanged();
  16. };

Providing the ImageViewer class has been registered using qmlRegisterType(), its Status enum can now be used from QML:

  1. ImageViewer  {
  2.     onStatusChanged:  {
  3.         if (status == ImageViewer.Ready)
  4.             console.log("Image viewer is ready!")
  5.     }
  6. }

The C++ type must be registered with QML to use its enums. If your C++ type is not instantiable, it can be registered using qmlRegisterUncreatableType(). To be accessible from QML, the names of enum values must begin with a capital letter.

See the Writing QML extensions with C++ tutorial and the Extending QML Functionalities using C++ reference documentation for more information.

Using enumeration values as signal parameters

C++ signals may pass enumeration values as signal parameters to QML, providing that the enumeration and the signal are declared within the same class, or that the enumeration value is one of those declared in the Qt Namespace.

Additionally, if a C++ signal with an enum parameter should be connectable to a QML function using the connect() function, the enum type must be registered using qRegisterMetaType().

For QML signals, enum values may be used as signal parameters using the int type:

  1. ImageViewer  {
  2.     signal someOtherSignal(int statusValue)
  3.  
  4.     Component.onCompleted:  {
  5.         someOtherSignal(ImageViewer.Loading)
  6.     }
  7. }

Automatic type conversion from strings

As a convenience, some basic types can be specified in QML using format strings to make it easier to pass simple values from QML to C++.

TypeString formatExample
QColorColor name, "#RRGGBB", "#RRGGBBAA""red", "#ff0000", "#ff000000"
QDate"YYYY-MM-DD""2010-05-31"
QPoint"x,y""10,20"
QRect"x,y,WidthxHeight""50,50,100x100"
QSize"WidthxHeight""100x200"
QTime"hh:mm:ss""14:22:55"
QUrlURL string"http://www.example.com"
QVector3D"x,y,z""0,1,0"
Enumeration valueEnum value name"AlignRight"

(More details on these string formats and types can be found in the basic type documentation.)

These string formats can be used to set QML property values and pass arguments to C++ functions. This is demonstrated by various examples on this page; in the above Qt properties example, the ApplicationData class has a backgroundColor property of a QColor type, which is set from the QML code with the string "red" rather rather than an actual QColor object.

If it is preferred to pass an explicitly-typed value rather than a string, the global Qt object provides convenience functions for creating some of the object types listed above. For example, Qt.rgba() creates a QColor value from four RGBA values. The QColor returned from this function could be used instead of a string to set a QColor-type property or to call a C++ function that requires a QColor parameter.

Writing QML plugins

The Qt Declarative module includes the QDeclarativeExtensionPlugin class, which is an abstract class for writing QML plugins. This allows QML extension types to be dynamically loaded into QML applications.

See the QDeclarativeExtensionPlugin documentation and How to Create Qt Plugins for more details.

Managing resource files with the Qt resource system

The Qt resource system allows resource files to be stored as binary files in an application executable. This can be useful when building a mixed QML/C++ application as it enables QML files (as well as other resources such as images and sound files) to be referred to through the resource system URI scheme rather than relative or absolute paths to filesystem resources. Note, however, that if you use the resource system, the application executable must be re-compiled whenever a QML source file is changed in order to update the resources in the package.

To use the resource system in a mixed QML/C++ application:

  • Create a .qrc resource collection file that lists resource files in XML format
  • From C++, load the main QML file as a resource using the :/ prefix or as a URL with the qrc scheme

Once this is done, all files specified by relative paths in QML will be loaded from the resource system instead. Use of the resource system is completely transparent to the QML layer; this means all QML code should refer to resource files using relative paths and should not use the qrc scheme. This scheme should only be used from C++ code for referring to resource files.

Here is a application packaged using the Qt resource system. The directory structure looks like this:

  1. project
  2.     |- example.qrc
  3.     |- main.qml
  4.     |- images
  5.         |- background.png
  6.     |- main.cpp
  7.     |- project.pro

The main.qml and background.png files will be packaged as resource files. This is done in the example.qrc resource collection file:

  1. <!DOCTYPE RCC>
  2. <RCC version="1.0">
  3.  
  4. <qresource prefix="/">
  5.     <file>main.qml</file>
  6.     <file>images/background.png</file>
  7.  
  8. </RCC>

Since background.png is a resource file, main.qml can refer to it using the relative path specified in example.qrc:

  1. // main.qml
  2. import QtQuick 1.0
  3.  
  4. Image  { source: "images/background.png" }

To allow QML to locate resource files correctly, the main.cpp loads the main QML file, main.qml, as a resource file using the qrc scheme:

  1. int main(int argc, char *argv[])
  2.  {
  3.     QApplication app(argc, argv);
  4.  
  5.     QDeclarativeView view;
  6.     view.setSource(QUrl("qrc:/main.qml"));
  7.     view.show();
  8.  
  9.     return app.exec();
  10. }

Finally project.pro uses the RESOURCES variable to indicate that example.qrc should be used to build the application resources:

  1. QT += declarative
  2.  
  3. SOURCES += main.cpp
  4. RESOURCES += example.qrc

See The Qt Resource System for more information.

Notes provided by the Qt Community
Informative
  • 5

Votes: 2

Coverage: Qt library 4.7, 4.8

Picture of sigrid sigrid

Lab Rat
20 notes

This person works for Qt Development Frameworks. Nokia Certified Qt Developer

Necessary to use QGraphicsItem functionality for custom painting

In the section “Defining new QML elements” it is advised against using QGraphicsItem functionality when subclassing QDeclarativeItem. Note however that if you want to implement your own painting for the item, the only option you have is to reimplement QGraphicsItem::paint()

[Revisions]

Informative
  • 4

Votes: 3

Coverage: Qt library 4.7, 4.8

Picture of sigrid sigrid

Lab Rat
20 notes

This person works for Qt Development Frameworks. Nokia Certified Qt Developer

Receiving signals in QML

Note that you need to name the signal arguments identically in C++ and QML when receiving signals with parameters in QML from C++. If the arguments are not named identically and you try to access the argument in QML, you will get errors similar to the following:

  1. theSignal  [object Object]
  2. aProperty undefined

So, when having the following signal:

  1. void somethingHappened(SomeClass event);

it needs to be accessed in QML as follows:

  1. onSomethingHappened: {
  2. console.log(" something happened " +event);
  3. console.log(" is it urgent? " + event.urgent);

for it to work.

[Revisions]