Request sent to Digia including this code:
main.cpp:
#include "Model.h"
#include <QDeclarativeContext>
#include <QDeclarativeView>
#include <QApplication>
#include <QTableView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDeclarativeView *view = new QDeclarativeView;
QDeclarativeContext *context = view->rootContext();
QTableView *table = new QTableView;
Model *model = new Model(0);
table->setModel(model);
view->setSource(QUrl("qrc:/qml/qmlview.qml"));
context->setContextProperty("listModel", model);
table->show(); // Accesses rowCount(), columnCount() and data() and can display a list of 2x2
view->show(); // Only accesses rowCount().
return a.exec();
}
model.h:
#ifndef MODEL_H
#define MODEL_H
#include <QModelIndex>
class Model : public QAbstractTableModel
{
Q_OBJECT
public:
Model(QObject *parent);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
};
#endif // MODEL_H
model.cpp:
#include "Model.h"
Model::Model(QObject *parent)
:QAbstractTableModel(parent)
{
}
int Model::rowCount(const QModelIndex &parent) const
{
return 2;
}
int Model::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant Model::data(const QModelIndex &index, int role) const
{
if(role == Qt::DisplayRole)
{
return QString("Row%1, Column%2")
.arg(index.row() + 1)
.arg(index.column() +1);
}
return QVariant();
}
qmlview.qml:
import QtQuick 1.1
Rectangle {
ListView {
id: listView
model: listModel
delegate: componentDelegate
}
Component {
id: componentDelegate
Text {
text: name // A request will be send to the model.
}
}
}
src.qrc:
<RCC>
<qresource prefix="/qml">
<file>qmlview.qml</file>
</qresource>
</RCC>
↧