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:

  1. import People 1.0
  2.  
  3. Person  {
  4.     name: "Bob Jones"
  5.     shoeSize: 12
  6. }

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.

  1. class Person : public QObject
  2.  {
  3.     Q_OBJECT
  4.     Q_PROPERTY(QString name READ name WRITE setName)
  5.     Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
  6. public:
  7.     Person(QObject *parent = 0);
  8.  
  9.     QString name() const;
  10.     void setName(const QString &);
  11.  
  12.     int shoeSize() const;
  13.     void setShoeSize(int);
  14.  
  15. private:
  16.     QString m_name;
  17.     int m_shoeSize;
  18. };

Define the Person class

  1. Person::Person(QObject *parent)
  2. : QObject(parent), m_shoeSize(0)
  3.  {
  4. }
  5.  
  6. QString Person::name() const
  7.  {
  8.     return m_name;
  9. }
  10.  
  11. void Person::setName(const QString &n)
  12.  {
  13.     m_name = n;
  14. }
  15.  
  16. int Person::shoeSize() const
  17.  {
  18.     return m_shoeSize;
  19. }
  20.  
  21. void Person::setShoeSize(int s)
  22.  {
  23.     m_shoeSize = s;
  24. }

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

The main.cpp file also calls the qmlRegisterType() function to register the Person type 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.

Notes provided by the Qt Community
Informative
  • 0

Votes: 0

Coverage: Qt library 4.7, 4.8, 5.0

Picture of sigrid sigrid

Lab Rat
20 notes

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

Namespace name has to be explicitly used for QML compatibility

The documentation above mentions that the C++ class can appear in a namespace. Note however that if a class is declared inside a namespace, then the namespace name has to be included when referencing to the class in Q_PROPERTY declarations and in associated read and write function prototypes. See the following Jira report [bugreports.qt.nokia.com] for more info on this.

[Revisions]