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

  1. #include <QtGui>
  2. #include <QtDeclarative>
  3.  
  4. namespace MyNamespace {
  5.  class Person : public QObject
  6.  {
  7.   Q_OBJECT
  8.    Q_PROPERTY(QString name READ name WRITE setName)
  9.    Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
  10.  public:
  11.   Person()
  12.   {}
  13.  
  14.   QString name() const
  15.   {
  16.    return m_name;
  17.   }
  18.   void setName(const QString & n)
  19.   {
  20.    m_name = n;
  21.   }
  22.  
  23.   int shoeSize() const
  24.   {
  25.    return m_size;
  26.   }
  27.   void setShoeSize(int s)
  28.   {
  29.    m_size = s;
  30.   }
  31.  
  32.  private:
  33.   QString m_name;
  34.   int m_size;
  35.  };
  36. }
  37.  
  38. #include "main.moc"
  39.  
  40. using namespace MyNamespace;
  41.  
  42. int main(int argc, char** argv)
  43. {
  44.  QApplication app(argc, argv);
  45.  qmlRegisterType<Person>("People", 1, 0, "Person");
  46.  MyNamespace::Person myObj;
  47.  QDeclarativeView view;
  48.  view.rootContext()->setContextProperty("rootItem", (Person *)&myObj);
  49.  view.setSource(QUrl::fromLocalFile("main.qml"));
  50.  view.resize(200,100);
  51.  view.show();
  52.  return app.exec();
  53. }

main.qml

  1. import QtQuick 1.0
  2. import People 1.0
  3.  
  4. Text {
  5.     text: myPerson.name
  6.    
  7.     Person {
  8.  id: myPerson;
  9.  name: "Sigurd"
  10.  shoeSize: 24
  11.  
  12.     }
  13. }

Categories: