This is a subject that I always have to look up myself, and I'm still a bit unsure, so there may be better ways than what I suggest. Anyway, it seems that QAbstractItemModel
doesn't provide the functions that you're trying to test. I can think of two ways to get around that.
Add them yourself
#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QQuickView>
#include <QDebug>
#include "qtquick2applicationviewer.h"
#include "QAbstractListModel"
class Model : public QAbstractListModel
{
Q_OBJECT
public:
Model() {}
int rowCount(const QModelIndex &parent) const
{
return mList.size();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const{
if (index.row() < 0 || index.row() >= mList.size()) {
return QVariant();
}
return mList.at(index.row());
}
Q_INVOKABLE QVariant get(int index) {
return data(createIndex(index, 0));
}
Q_INVOKABLE void append(QVariant element) {
beginInsertRows(QModelIndex(), mList.size() + 1, mList.size() + 1);
mList.append(element.toMap().value("name").toString());
endInsertRows();
}
private:
QList<QString> mList;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
Model model;
viewer.rootContext()->setContextProperty("model", &model);
viewer.setMainQmlFile(QStringLiteral("qml/quick/main.qml"));
viewer.showExpanded();
return app.exec();
}
#include "main.moc"
Here's a small hack of a QML test case:
import QtQuick 2.2
Item {
width: 360
height: 360
Component.onCompleted: {
model.append({name: "blah"});
console.assert(model.get(0) === "blah");
}
}
Use QQmlListProperty
This is only useful if your model is or can be wrapped by a QObject
subclass, as it is, as its name suggests, used as a property of an object. It's useful for it's convenience, but is less flexible than the first option, as it can only store QObject
-derived object pointers. I won't go into details on this, as I'm assuming that this is not relevant for your use case.
You can find more information below: