Extending QML with a C++ class in a custom namespace
The example code below shows how you can extend QML with a C++ class in a custom namespace.
main.cpp
- #include <QtGui>
- #include <QtDeclarative>
- namespace MyNamespace {
- {
- Q_OBJECT
- Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
- public:
- Person()
- {}
- {
- return m_name;
- }
- {
- m_name = n;
- }
- int shoeSize() const
- {
- return m_size;
- }
- void setShoeSize(int s)
- {
- m_size = s;
- }
- private:
- QString m_name;
- int m_size;
- };
- }
- #include "main.moc"
- using namespace MyNamespace;
- int main(int argc, char** argv)
- {
- qmlRegisterType<Person>("People", 1, 0, "Person");
- MyNamespace::Person myObj;
- QDeclarativeView view;
- view.rootContext()->setContextProperty("rootItem", (Person *)&myObj);
- view.resize(200,100);
- view.show();
- return app.exec();
- }
main.qml
- import QtQuick 1.0
- import People 1.0
- Text {
- text: myPerson.name
- Person {
- id: myPerson;
- name: "Sigurd"
- shoeSize: 24
- }
- }

