herophuong
herophuong

Reputation: 364

Change QML GridView model by javascript

I have one ListView and one GridView. Imagine it like this: The first view presents the categories and the second view presents article in each category. I want to dynamically change the data model of the GridView when the current index of the ListView change by javascript. How do we do that?

Upvotes: 2

Views: 1350

Answers (2)

sergk
sergk

Reputation: 3631

Depends on your models. Assuming CategoriesModel has category role, and ArticlesModel has setCategory method:

ListView {
    model: CategoriesModel {}
    delegate: Item {
        MouseArea {
            anchors.fill: parent
            onClicked: {
                grid_view.model.setCategory(model.category)
            }
        }
        // ...
    }
}

GridView {
    id: grid_view
    model: ArticlesModel {}
    // ...
}

Upvotes: 3

MartinJ
MartinJ

Reputation: 1701

You simply need to assign a new model. Here's one example, based on the ListModel docs. This model shows the fruit in the model in the ListView on the left. When a delegate is clicked, it sets the model for the GridView on the right to the list defined by the attributes role.

import QtQuick 1.0

Item {
    width: 600; height: 400

    ListView {
        width: 300; height: 400
        model: fruitModel
        delegate: Text {
            font.pixelSize: 20
            text: name
            width: 300
            MouseArea {
                anchors.fill: parent
                onClicked: grid.model = attributes
            }
        }
    }

    GridView {
        id: grid
        x: 300; width: 300; height: 400
        delegate: Text {
            text: description
            font.pixelSize: 20
        }
    }

    ListModel {
     id: fruitModel

     ListElement {
         name: "Apple"
         cost: 2.45
         attributes: [
             ListElement { description: "Core" },
             ListElement { description: "Deciduous" }
         ]
     }
     ListElement {
         name: "Orange"
         cost: 3.25
         attributes: [
             ListElement { description: "Citrus" }
         ]
     }
     ListElement {
         name: "Banana"
         cost: 1.95
         attributes: [
             ListElement { description: "Tropical" },
             ListElement { description: "Seedless" }
         ]
     }
    }
}

This is an example of a nested model, but there are other possibilities. For example, if you're sourcing your data from a database, perhaps you just need to change the query used by the GridView's model, rather than setting a different model.

Upvotes: 3

Related Questions