QML案例:objectlistmodel
- 参考:Qt官方案例
- 模型管理数据,视图管理代理。
- dataobject.h
#ifndef DATAOBJECT_H #define DATAOBJECT_H #include <QObject> class DataObject : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged) public: DataObject(QObject *parent=0); DataObject(const QString &name, const QString &color, QObject *parent=0); QString name() const; void setName(const QString &name); QString color() const; void setColor(const QString &color); signals: void nameChanged(); void colorChanged(); private: QString m_name; QString m_color; }; #endif // DATAOBJECT_H
- dataobject.cpp
#include <QDebug> #include "dataobject.h" DataObject::DataObject(QObject *parent) : QObject(parent) { } DataObject::DataObject(const QString &name, const QString &color, QObject *parent) : QObject(parent), m_name(name), m_color(color) { } QString DataObject::name() const { return m_name; } void DataObject::setName(const QString &name) { if (name != m_name) { m_name = name; emit nameChanged(); } } QString DataObject::color() const { return m_color; } void DataObject::setColor(const QString &color) { if (color != m_color) { m_color = color; emit colorChanged(); } }
- main.cpp
#include <QGuiApplication> #include <qqmlengine.h> #include <qqmlcontext.h> #include <qqml.h> #include <QtQuick/qquickitem.h> #include <QtQuick/qquickview.h> #include "dataobject.h" /* This example illustrates exposing a QList<QObject*> as a model in QML */ int main(int argc, char ** argv) { QGuiApplication app(argc, argv); QList<QObject*> dataList; dataList.append(new DataObject("Item 1", "red")); dataList.append(new DataObject("Item 2", "green")); dataList.append(new DataObject("Item 3", "blue")); dataList.append(new DataObject("Item 4", "yellow")); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); QQmlContext *ctxt = view.rootContext(); ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); view.setSource(QUrl("qrc:view.qml")); view.show(); return app.exec(); }
- viem.qml
import QtQuick 2.0 ListView { width: 400; height: 300 model: myModel delegate: Rectangle { height: 35 width: 80 color: model.modelData.color Text { text: name } } }