Home · All Classes · All Functions · Overviews

Extending QML - Adding Types Example

Files:

The Adding Types Example shows how to add a new element type, Person, to QML. The Person type can be used from QML like this:

 Person {
     name: "Bob Jones"
     shoeSize: 12
 }

Declare the Person class

All QML elements map to C++ types. Here we declare a basic C++ Person class with the two properties we want accessible on the QML type - name and shoeSize. Although in this example we use the same name for the C++ class as the QML element, the C++ class can be named differently, or appear in a namespace.

 #include <qdeclarative.h>

 class Person : public QObject {
 Q_OBJECT
 Q_PROPERTY(QString name READ name WRITE setName)
 Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
 public:
     Person(QObject *parent = 0);

     QString name() const;
     void setName(const QString &);

     int shoeSize() const;
     void setShoeSize(int);
 private:
     QString m_name;
     int m_shoeSize;
 };
 QML_DECLARE_TYPE(Person);

Following the class declaration, we include the QML_DECLARE_TYPE() macro. This is necessary to declare the type to QML. It also includes the logic necessary to expose the class to Qt's meta system - that is, it includes the Q_DECLARE_METATYPE() functionality.

Define the Person class

 Person::Person(QObject *parent)
 : QObject(parent), m_shoeSize(0)
 {
 }

 QString Person::name() const
 {
     return m_name;
 }

 void Person::setName(const QString &n)
 {
     m_name = n;
 }

 int Person::shoeSize() const
 {
     return m_shoeSize;
 }

 void Person::setShoeSize(int s)
 {
     m_shoeSize = s;
 }

The Person class implementation is quite basic. The property accessors simply return members of the object instance.

The implementation must also be registered using the QML_REGISTER_TYPE() macro. This macro registers the Person class with QML as a type in the People library version 1.0, and defines the mapping between the C++ and QML class names.

Running the example

The main.cpp file in the example includes a simple shell application that loads and runs the QML snippet shown at the beginning of this page.


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt 4.7.0