How can I use a QObject (subclass) in qml?

The QML engine has no intrinsic knowledge of any class types. Instead the programmer must register the C++ types with their corresponding QML names. This can be done using qmlRegisterType() [doc.qt.nokia.com]. When having registered the type, you can use it in qml as shown in the following example:

main.cpp

  1. #include <QtGui>
  2. #include <QDeclarativeEngine>
  3. #include <QDeclarativeView>
  4. #include <QtDeclarative>
  5.  
  6. class MyObject : public QObject
  7. {
  8.         Q_OBJECT
  9. public:
  10.         MyObject()
  11.         {}
  12.         public slots:
  13.                 QObject * getObject()
  14.                 {
  15.                         return new MyObject();
  16.                 }
  17. };
  18.  
  19. #include "main.moc"
  20.  
  21. int main(int argc, char** argv)
  22. {
  23.         QApplication app(argc, argv);
  24.         QDeclarativeView view;
  25.         qmlRegisterType<MyObject>("QtQuick", 1, 0, "MyObject");
  26.         view.setSource(QUrl::fromLocalFile("c:/testOwnership/test.qml"));
  27.         view.show();
  28.         return app.exec();
  29.  
  30. }

test.qml

  1. import QtQuick 1.0
  2.  
  3.  Rectangle {
  4.      id: page
  5.      width: 500; height: 200
  6.      color: "lightgray"
  7.  
  8.      MyObject
  9.      {
  10.         id: myObject
  11.                 Component.onCompleted: {
  12.                     print("completed..." + myObject.getInfo);
  13.                     var obj = myObject.getInfo();
  14.                  
  15.                 }}}

No comments

Write a comment

Sorry, you must be logged in to post a comment.