[Qt-qml] C++ Data Models and plugin mechanism

warwick.allison at nokia.com warwick.allison at nokia.com
Tue May 18 00:34:57 CEST 2010


> So you can only extend QML Data Model by reimplementing
> QDeclarativeView. Am I correct?

Fortunately not. setContextProperty is just ONE way of creating an identified object.

To make a model as a type in a plugin, just inherit your type from QAbstractItemModel (rather than QDeclarativeItem as you would for an item type plugin), register the type in the normal plugin manner:

        qmlRegisterType<MyModel>(uri,1,0, "MyModel");

Then you can instantiate your model from QML, giving it whatever id you like, then using it in views:

import myplugin 1.0
Item {
   ...
   MyModel { id: myPluggedInModel }
   ListView { model: myPluggedInModel; ... }
}

Plugins can provide any type that subclasses QObject, and QML code can then import that plugin and instantiate the type.

If you want a more simple model, such as the QStringList example in to C++ model documentation, you could make your plugin type just a simple QObject with the stringlist as a property:

class MyObj : public QObject {
	Q_OBJECT
	Q_PROPERTY(QStringList myModel READ myModel);
	QStringList myModel() const { return QStringList() << "Fred" << "Ginger" << "Skipper"; }
};

Register as normal:

        qmlRegisterType<MyObj>(uri,1,0, "MyObj");

then:

import myplugin 1.0
Item {
   ...
   MyObjl { id: myPluggedInObj }
   ListView { model: myPluggedInObj.myModel; ... }
}


I'll improve the docs in this regard.

--
Warwick




More information about the Qt-qml mailing list