Thursday 9 January 2014

Load data from another qml file and show it in ListView

From below doc, you will see some code snippet which shows how to create a simple ListView.
http://doc-snapshot.qt-project.org/qdoc/qml-qtquick-listview.html#model-prop

I assemble them and put them in one demo app. In my project, the folder tree is:
listview1$ tree
.
├── imports
│   └── model
│       ├── ContactModel.qml
│       └── qmldir
├── run.sh
└── test.qml
This demo app contains one test.qml and another plugin which only contains one ContactModel.qml file without C++ dynamic library.
qmldir describes the module exposed from plugin
module model
ContactModel 1.0 ContactModel.qml
The ContactModel.qml is a model for ListView to provide data.
import QtQuick 2.0
ListModel {
    ListElement {
        name: "Bill Smith"
        number: "555 3264"
    }
    ListElement {
        name: "John Brown"
        number: "555 8426"
    }
    ListElement {
        name: "Sam Wise"
        number: "555 0473"
    }
}
In test.qml file, apply ContactModel to model attribute. The delegate is a way to iterate all ListElements provided by model and show each element as one Text block on Window.
import QtQuick 2.0
import model 1.0
ListView {
    width: 180; height: 200
    model: ContactModel {}
    delegate: Text {
        text: name + ": " + number
    }
}
 To build this, just call following commands:
qmake
make
To run it:
~/Qt5.2.0/5.2.0/gcc_64/bin/qmlscene -I ./imports ./test.qml

No comments:

Followers

Contributors