Supported data types

Any C++ data that is used from QML -whetheras custom properties, or parameters for signals or functions - must beof a typethat is recognizable by QML.

By default, QML recognizes thefollowingdata types:

·        bool

·        unsigned int, int

·        float, double, qreal

·        QString

·        QUrl

·        QColor

·        QDateQTimeQDateTime

·        QPointQPointF

·        QSizeQSizeF

·        QRectQRectF

·        QVariant

·        QVariantListQVariantMap

·        QObject*

·        Enumerations declared with Q_ENUMS()

To allow a custom C++ type to be createdorused in QML, the C++ class must be registered as a QML type using qmlRegisterType(),asshown in the Defining new QML elements sectionabove.

JavaScript arrays andobjects

There is built-in support for automatictypeconversion between QVariantList andJavaScript arrays,and QVariantMap andJavaScript objects.

For example, the function defined inQMLbelow left expects two arguments, an array and an object, and printstheircontents using the standard JavaScript syntax for array and object itemaccess.The C++ code below right calls this function, passing a QVariantList anda QVariantMap,whichare 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])


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"));


4.   QVariantList list;

5.   list << 10 << Qt::green << "bottles";


7.   QVariantMap map;

8.   map.insert("language""QML");

9.   map.insert("released"QDate(2010, 9, 21));


11.  QMetaObject::invokeMethod(view.rootObject(),"readValues",

12.          Q_ARG(QVariant,QVariant::fromValue(list)),

   13.       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 = TueSep 21 2010 00:00:00 GMT+1000 (EST)

Similarly, if a C++ type uses a QVariantList or QVariantMap typefor a property ormethod parameter, the value can be created as a JavaScriptarray or object in theQML side, and is automatically converted to a QVariantList or QVariantMap whenit is passed to C++.

Using enumerations of acustom type

To use an enumeration from a customC++component, the enumeration must be declared with Q_ENUMS() toregisterit with Qt's meta object system. For example, the following C++ typehas a Status enum:

1.   class ImageViewer : public QDeclarativeItem

2.    {

3.       Q_OBJECT

4.       Q_ENUMS(Status)

5.       Q_PROPERTY(Status status READstatus NOTIFYstatusChanged)

6.   public:

7.       enum Status  {

8.           Ready,

9.           Loading,

10.          Error

11.      };


13.      Status status() const;

14.  signals:

15.      void statusChanged();

16.  };

Providing the ImageViewer class has been registeredusing qmlRegisterType(),its Status enum can now be used fromQML:

1.   ImageViewer  {

2.       onStatusChanged:  {

3.           if (status == ImageViewer.Ready)

4.             console.log("Image viewer isready!")

5.       }

6.   }

The C++ type must be registered with QMLtouse its enums. If your C++ type is not instantiable, it can be registeredusing qmlRegisterUncreatableType().Tobe accessible from QML, the names of enum values must begin with acapitalletter.

See the Writing QML extensions with C++ tutorialand the Extending QMLFunctionalitiesusing C++reference documentation for more information.

Using enumeration valuesas signalparameters

C++ signals may pass enumeration valuesassignal parameters to QML, providing that the enumeration and the signalaredeclared within the same class, or that the enumeration value is one ofthosedeclared in the Qt Namespace.

Additionally, if a C++ signal with anenumparameter 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 usedassignal parameters using the int type:

1.   ImageViewer  {

2.       signal someOtherSignal(int statusValue)


4.      Component.onCompleted:  {

5.          someOtherSignal(ImageViewer.Loading)

6.       }

7.   }

Automatic type conversionfrom strings

As a convenience, some basic types canbespecified in QML using format strings to make it easier to pass simplevaluesfrom QML to C++.


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

These string formats can be used to setQML property values and passargumentsto C++ functions. This is demonstrated by various examples on thispage; in theabove Qt properties example,theApplicationData class has a backgroundColor property of a QColor type,which is set fromthe QML code with the string "red" rather ratherthan an actual QColor object.

If it is preferred to pass anexplicitly-typedvalue rather than a string, the global Qt objectprovidesconveniencefunctions for creating some of the object types listed above. Forexample,Qt.rgba() createsa QColor valuefrom four RGBAvalues. The QColor returnedfrom thisfunction could be used instead of a string to set a QColor-typepropertyor to call a C++ function that requires aQColor parameter.

Writing QML plugins

The Qt Declarative module includesthe QDeclarativeExtensionPlugin class,which is anabstract class for writing QML plugins. This allows QML extensiontypes to bedynamically loaded into QML applications.

See the QDeclarativeExtensionPlugin documentationand How to Create Qt Plugins formore details.

Managing resource files with the Qtresourcesystem

The Qt resource system allowsresource files tobe stored as binary files in an application executable. Thiscan be useful whenbuilding a mixed QML/C++ application as it enables QML files(as well as otherresources such as images and sound files) to be referred tothrough theresource system URI scheme rather than relative or absolute paths tofilesystemresources. Note, however, that if you use the resource system, theapplicationexecutable must be re-compiled whenever a QML source file is changedin orderto update the resources in the package.

To use the resource system in amixedQML/C++ application:

·        Create a .qrc resource collection file thatlistsresource files in XML format

·        From C++, load the main QML file as aresource using the :/ prefix oras aURL with the qrcscheme

Once this is done, all files specifiedbyrelative paths in QML will be loaded from the resource system instead. Useofthe resource system is completely transparent to the QML layer; this meansallQML code should refer to resource files using relative paths andshould not use the qrc scheme. This schemeshould only beused from C++ code for referring to resource files.

Here is a application packaged usingthe Qt resource system.Thedirectory structure looks like this:

1.   project

2.       |- example.qrc

3.       |- main.qml

4.       |- images

5.           |- background.png

6.       |- main.cpp

7.       |-

The main.qml and background.png files will bepackaged asresource files. This is done in theexample.qrc resource collection file:


2.   <RCC version="1.0">


4.   <qresource prefix="/">

5.      <file>main.qml</file>

6.      <file>images/background.png</file>

7.   </qresource>


9.   </RCC>

Since background.png is a resourcefile, main.qml can refer to itusing therelative path specified in example.qrc:

1.   //main.qml

2.   import QtQuick 1.0


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

To allow QML to locate resource filescorrectly,the main.cpp loads the main QMLfile, main.qml, as a resource fileusingthe qrc scheme:

1.   int main(int argc, char *argv[])

2.    {

3.       QApplication app(argc, argv);


5.       QDeclarativeView view;

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



9.       return app.exec();

10.  }

Finally uses the RESOURCESvariable to indicatethat example.qrc should be used tobuildthe application resources:

1.   QT += declarative


3.   SOURCES += main.cpp

4.   RESOURCES += example.qrc

See The Qt Resource System formore information.

Related Links

·        Extending QML Functionalitiesusing C++

·        Integrating QML Code withExisting Qt UI Code