这次加载的数据来自于C++动态库而不是另一个qml文件。这个比之前的文章复杂。
我的项目目录树如下:
/listview2$ tree . ├── imports │ └── mylist │ ├── libmylist.so │ └── qmldir ├── list2.pro ├── plugin.cpp ├── run.sh └── test.qml
TEMPLATE = lib CONFIG += plugin QT += qml DESTDIR = imports/mylist TARGET = mylist SOURCES += plugin.cpp qml.files = test.qml qml.path += ./ pluginfiles.files += imports/mylist/qmldir pluginfiles.path += imports/mylist target.path += imports/mylist INSTALLS += target qml pluginfiles
module mylist plugin mylist
#include <QtQml/QQmlExtensionPlugin> #include <QtQml/qqml.h> #include <qdebug.h> #include <qdatetime.h> #include <qbasictimer.h> #include <qcoreapplication.h> #include <QAbstractItemModel> #include <QStringList> class People { public: People(QString const & name, QString const & number) : name_(name), number_(number) { } QString name() const { return name_; } QString number() const { return number_; } private: QString name_; QString number_; }; class PeopleListModel : public QAbstractListModel { Q_OBJECT public: enum PeopleRoles { NameRole = Qt::UserRole + 1, NumberRole }; PeopleListModel(QObject * parent = 0) : QAbstractListModel(parent) { People p1("Dean", "186***"); addPeople(p1); People p2("Crystal", "186***"); addPeople(p2); } void addPeople(People const & p) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); values_ << p; endInsertRows(); } int rowCount(QModelIndex const & parent = QModelIndex()) const { return values_.count(); } QVariant data(QModelIndex const & index, int role = Qt::DisplayRole) const { if (index.row() < 0 || index.row() >= values_.count()) return QVariant(); People const & p = values_[index.row()]; if (role == NameRole) return p.name(); else if (role == NumberRole) return p.number(); return QVariant(); } protected: QHash<int, QByteArray> roleNames() const { QHash<int, QByteArray> roles; roles[NameRole] = "name"; roles[NumberRole] = "number"; return roles; } private: QList<People> values_; }; class QExampleQmlPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtension.PeopleListModel") public: void registerTypes(char const * uri) { qmlRegisterType<PeopleListModel>(uri, 1, 0, "PeopleListModel"); } }; #include "plugin.moc"
PeopleListModel类继承自QAbstractListModel, 它提供了ListView需要的数据。
QExampleQmlPlugin类是plugin类,注册了PeopleListModel类。
注意PeopleListModel类的三个方法:rowCount, data和roleNames. 它们都是ListView需要的。
要想理解Model-View体系结构,请从下面的文档开始。
http://doc-snapshot.qt-project.org/qdoc/model-view-programming.html#introduction-to-model-view-programming