Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

Animation and TransitionsPresenting Data with Views

QML Data Models

QML items such asListView,GridView andRepeater require Data Models that provide the data to be displayed. These items typically require adelegate component that creates an instance for each item in the model. Models may be static, or have items modified, inserted, removed or moved dynamically.

Data is provided to the delegate via named data roles which the delegate may bind to. Here is aListModel with two roles,type andage, and aListView with a delegate that binds to these roles to display their values:

import QtQuick 1.0Item {width:200;height:250ListModel {id:myModelListElement {type:"Dog";age:8 }ListElement {type:"Cat";age:5 }    }Component {id:myDelegateText {text:type+", "+age }    }ListView {anchors.fill:parentmodel:myModeldelegate:myDelegate    }}

If there is a naming clash between the model's properties and the delegate's properties, the roles can be accessed with the qualifiedmodel name instead. For example, if aText element hadtype orage properties, the text in the above example would display those property values instead of thetype andage values from the model item. In this case, the properties could have been referenced asmodel.type andmodel.age instead to ensure the delegate displays the property values from the model item.

A specialindex role containing the index of the item in the model is also available to the delegate. Note this index is set to -1 if the item is removed from the model. If you bind to the index role, be sure that the logic accounts for the possibility of index being -1, i.e. that the item is no longer valid. (Usually the item will shortly be destroyed, but it is possible to delay delegate destruction in some views via adelayRemove attached property.)

Models that do not have named roles (such as theQStringList model shown below) will have the data provided via themodelData role. ThemodelData role is also provided for models that have only one role. In this case themodelData role contains the same data as the named role.

QML provides several types of data models among the built-in set of QML elements. In addition, models can be created with C++ and then made available to QML components.

The views used to access data models are described in thePresenting Data with Views overview. The use of positioner items to arrange items from a model is covered inUsing QML Positioner and Repeater Items.

QML Data Models

ListModel

ListModel is a simple hierarchy of elements specified in QML. The available roles are specified by theListElement properties.

ListModel {id:fruitModelListElement {name:"Apple"cost:2.45    }ListElement {name:"Orange"cost:3.25    }ListElement {name:"Banana"cost:1.95    }}

The above model has two roles,name andcost. These can be bound to by aListView delegate, for example:

ListView {anchors.fill:parentmodel:fruitModeldelegate:Row {Text {text:"Fruit: "+name }Text {text:"Cost: $"+cost }    }}

ListModel provides methods to manipulate theListModel directly via JavaScript. In this case, the first item inserted determines the roles available to any views that are using the model. For example, if an emptyListModel is created and populated via JavaScript, the roles provided by the first insertion are the only roles that will be shown in the view:

ListModel {id:fruitModel }    ...MouseArea {anchors.fill:parentonClicked:fruitModel.append({"cost":5.95, "name":"Pizza"})}

When theMouseArea is clicked,fruitModel will have two roles,cost andname. Even if subsequent roles are added, only the first two will be handled by views using the model. To reset the roles available in the model, callListModel::clear().

XmlListModel

XmlListModel allows construction of a model from an XML data source. The roles are specified via theXmlRole element.

The following model has three roles,title,link anddescription:

XmlListModel {id:feedModelsource:"http://rss.news.yahoo.com/rss/oceania"query:"/rss/channel/item"XmlRole {name:"title";query:"title/string()" }XmlRole {name:"link";query:"link/string()" }XmlRole {name:"description";query:"description/string()" }}

TheRSS News demo shows howXmlListModel can be used to display an RSS feed.

VisualItemModel

VisualItemModel allows QML items to be provided as a model.

This model contains both the data and delegate; the child items of aVisualItemModel provide the contents of the delegate. The model does not provide any roles.

VisualItemModel {id:itemModelRectangle {height:30;width:80;color:"red" }Rectangle {height:30;width:80;color:"green" }Rectangle {height:30;width:80;color:"blue" }}ListView {anchors.fill:parentmodel:itemModel}

Note that in the above example there is no delegate required. The items of the model itself provide the visual elements that will be positioned by the view.

C++ Data Models

Models can be defined in C++ and then made available to QML. This is useful for exposing existing C++ data models or otherwise complex datasets to QML.

A C++ model class can be defined as aQStringList, aQList<QObject*> or aQAbstractItemModel. The first two are useful for exposing simpler datasets, whileQAbstractItemModel provides a more flexible solution for more complex models.

QStringList-based model

A model may be a simpleQStringList, which provides the contents of the list via themodelData role.

Here is aListView with a delegate that references its model item's value using themodelData role:

A Qt application can load this QML document and set the value ofmyModel to aQStringList:

QStringList dataList;    dataList.append("Item 1");    dataList.append("Item 2");    dataList.append("Item 3");    dataList.append("Item 4");QDeclarativeContext*ctxt= viewer.rootContext();    ctxt->setContextProperty("myModel",QVariant::fromValue(dataList));

The complete example is available in Qt'sexamples/declarative/modelviews/stringlistmodel directory.

Note:There is no way for the view to know that the contents of aQStringList have changed. If theQStringList changes, it will be necessary to reset the model by callingQDeclarativeContext::setContextProperty() again.

QObjectList-based model

A list ofQObject* values can also be used as a model. AQList<QObject*> provides the properties of the objects in the list as roles.

The following application creates aDataObject class that withQ_PROPERTY values that will be accessible as named roles when aQList<DataObject*> is exposed to QML:

class DataObject :publicQObject{    Q_OBJECT    Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)    Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)    ...};int main(int argc,char** argv){QApplication app(argc, argv);    QmlApplicationViewer viewer;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"));QDeclarativeContext*ctxt= viewer.rootContext();    ctxt->setContextProperty("myModel",QVariant::fromValue(dataList));    ...

TheQObject* is available as themodelData property. As a convenience, the properties of the object are also made available directly in the delegate's context. Here,view.qml references theDataModel properties in theListView delegate:

Note the use of the fully qualified access to thecolor property. The properties of the object are not replicated in themodel object, since they are easily available via themodelData object.

The complete example is available in Qt'sexamples/declarative/modelviews/objectlistmodel directory.

Note: There is no way for the view to know that the contents of aQList have changed. If theQList changes, it will be necessary to reset the model by callingQDeclarativeContext::setContextProperty() again.

QAbstractItemModel

A model can be defined by subclassingQAbstractItemModel. This is the best approach if you have a more complex model that cannot be supported by the other approaches. AQAbstractItemModel can also automatically notify a QML view when the model data has changed.

The roles of aQAbstractItemModel subclass can be exposed to QML by callingQAbstractItemModel::setRoleNames(). The default role names set by Qt are:

Qt RoleQML Role Name
Qt::DisplayRoledisplay
Qt::DecorationRoledecoration

Here is an application with aQAbstractListModel subclass namedAnimalModel that hastype andsize roles. It callsQAbstractItemModel::setRoleNames() to set the role names for accessing the properties via QML:

class Animal{public:    Animal(constQString&type,constQString&size);    ...};class AnimalModel :publicQAbstractListModel{    Q_OBJECTpublic:enum AnimalRoles {        TypeRole=Qt::UserRole+1,        SizeRole    };    AnimalModel(QObject*parent=0);    ...};AnimalModel::AnimalModel(QObject*parent)    :QAbstractListModel(parent){QHash<int,QByteArray> roles;    roles[TypeRole]="type";    roles[SizeRole]="size";    setRoleNames(roles);}int main(int argc,char** argv){QApplication app(argc, argv);    QmlApplicationViewer viewer;    AnimalModel model;    model.addAnimal(Animal("Wolf","Medium"));    model.addAnimal(Animal("Polar bear","Large"));    model.addAnimal(Animal("Quoll","Small"));QDeclarativeContext*ctxt= viewer.rootContext();    ctxt->setContextProperty("myModel",&model);    ...

This model is displayed by aListView delegate that accesses thetype andsize roles:

QML views are automatically updated when the model changes. Remember the model must follow the standard rules for model changes and notify the view when the model has changed by usingQAbstractItemModel::dataChanged(),QAbstractItemModel::beginInsertRows(), etc. See theModel subclassing reference for more information.

The complete example is available in Qt'sexamples/declarative/modelviews/abstractitemmodel directory.

QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML can only display list data. In order to display child lists of a hierarchical model theVisualDataModel element provides several properties and functions for use with models of typeQAbstractItemModel:

Exposing C++ Data Models to QML

The above examples useQDeclarativeContext::setContextProperty() to set model values directly in QML components. An alternative to this is to register the C++ model class as a QML type from a QML C++ plugin usingQDeclarativeExtensionPlugin. This would allow the model classes to be created directly as elements within QML:

class MyModelPlugin :publicQDeclarativeExtensionPlugin{public:void registerTypes(constchar*uri)    {        qmlRegisterType<MyModel>(uri,1,0,"MyModel");    }}Q_EXPORT_PLUGIN2(mymodelplugin, MyModelPlugin);
MyModel {id:myModelListElement {someProperty:"some value" }}
ListView {width:200;height:250model:myModeldelegate:Text {text:someProperty }}

SeeTutorial: Writing QML extensions with C++ for details on writing QML C++ plugins.

Other Data Models

An Integer

An integer can be used to specify a model that contains a certain number of elements. In this case, the model does not have any data roles.

The following example creates aListView with five elements:

Item {width:200;height:250Component {id:itemDelegateText {text:"I am item number: "+index }    }ListView {anchors.fill:parentmodel:5delegate:itemDelegate    }}

An Object Instance

An object instance can be used to specify a model with a single object element. The properties of the object are provided as roles.

The example below creates a list with one item, showing the color of themyText text. Note the use of the fully qualifiedmodel.color property to avoid clashing withcolor property of the Text element in the delegate.

Rectangle {width:200;height:250Text {id:myTexttext:"Hello"color:"#dd44ee"    }Component {id:myDelegateText {text:model.color }    }ListView {anchors.fill:parentanchors.topMargin:30model:myTextdelegate:myDelegate    }}

Accessing Views and Models from Delegates

You can access the view for which a delegate is used, and its properties, by usingListView.view in a delegate on aListView, orGridView.view in a delegate on aGridView, etc. In particular, you can access the model and its properties by usingListView.view.model.

This is useful when you want to use the same delegate for a number of views, for example, but you want decorations or other features to be different for each view, and you would like these different settings to be properties of each of the views. Similarly, it might be of interest to access or show some properties of the model.

In the following example, the delegate shows the propertylanguage of the model, and the color of one of the fields depends on the propertyfruit_color of the view.

Rectangle {width:200;height:200ListModel {id:fruitModel        propertystringlanguage:"en"ListElement {name:"Apple"cost:2.45        }ListElement {name:"Orange"cost:3.25        }ListElement {name:"Banana"cost:1.95        }    }Component {id:fruitDelegateRow {id:fruitText {text:" Fruit: "+name;color:fruit.ListView.view.fruit_color }Text {text:" Cost: $"+cost }Text {text:" Language: "+fruit.ListView.view.model.language }        }    }ListView {        propertycolorfruit_color:"green"model:fruitModeldelegate:fruitDelegateanchors.fill:parent    }}

Another important case is when some action (e.g. mouse click) in the delegate should update data in the model. In this case you can define a function in the model, e.g.:

        setData(int row,constQString& field_name,QVariant new_value),

...and call it from the delegate using:

ListView.view.model.setData(index,field,value)

...assuming thatfield holds the name of the field which should be updated, and thatvalue holds the new value.

Animation and TransitionsPresenting Data with Views

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp