BastiBen
BastiBen

Reputation: 19870

Qt/QML: How to refer to a component/object from a GridView's model's ListElement

I have a GridView with a delegate that is supposed to use a Loader to load and display components which are defined in the same QML file.

Let's say I have a GridView like this:

GridView {
    delegate: Rectangle {
        Loader { sourceComponent: model.pageContents }
    }
    model: ListModel {
        ListElement { /* how do I reference any of the components defined below from here, so the Loader can actually load and display it...  ? */ }
    }
}



Component {
    id: page_01
    Rectangle { 
        color: "red"
        // Page contents for page 1 go here.
    }
}



Component {
    id: page_02
    Rectangle { 
        color: "red"
        // Page contents for page 2 go here.
    }
}

I know I can create QML objects and components from Strings, external files and URLs. But I'd like to ideally do something like this:

ListModel {
    ListElement { pageContents: page_01 }
    ListElement { pageContents: page_02 }
}

I'd prefer to keep everything in a single QML file, so I can easily transfer and store it on the device without having to worry about resolving external dependencies, etc.

How do I refer to components in the same QML file from within ListElements?

Upvotes: 0

Views: 1407

Answers (1)

folibis
folibis

Reputation: 12864

Due to ListElement values limitation you cannot just put item id here. But you easily can use some external storage, for example property to store pointers to your pages. In example below I use array with pages ids and an index to wanted page as ListElement data:

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true
    width: 600
    height: 600

    GridView {
        id: grid
        anchors.fill: parent
        property var pages: [page_01, page_02]
        model: ListModel {
            ListElement { pageIndex: 0 }
            ListElement { pageIndex: 1 }
        }

        delegate: Loader { sourceComponent: grid.pages[pageIndex] }
    }

    Component {
        id: page_01
        Rectangle {
            color: "red"
            width: 100
            height: 100
            Component.onCompleted: console.log("page_01 was created")
        }
    }

    Component {
        id: page_02
        Rectangle {
            color: "blue"
            width: 100
            height: 100
            Component.onCompleted: console.log("page_02 was created")
        }
    }
}

Upvotes: 1

Related Questions