Extending QML - Adding Types Example#

Exporting C++ Classes.

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

<Code snippet "referenceexamples/adding/example.qml:0" not found>

Declare the Person Class#

All QML types 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 type, the C++ class can be named differently, or appear in a namespace.

class Person(QObject):

    Q_PROPERTY(QString name READ name WRITE setName)
    Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
# public
    QObject.QObject = using()
    name = QString()
    def setName():
    shoeSize = int()
    def setShoeSize(int):
# private
    m_name = QString()
    m_shoeSize = 0

Define the Person Class#

<Code snippet "referenceexamples/adding/person.cpp:0" not found>

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

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.

Example project @ code.qt.io