這次加載的數據來自於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#include #include #include #include #include #include #include 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 roleNames() const { QHash roles; roles[NameRole] = "name"; roles[NumberRole] = "number"; return roles; } private: QList values_; }; class QExampleQmlPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtension.PeopleListModel") public: void registerTypes(char const * uri) { qmlRegisterType (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