QML:使用Model/View框架時根據不同的數據項使用不同的delegate

Qt自帶的QML使用Model/View框架的example中,展示數據使用的delegate(似乎)都是唯一的,不能根據不同的Model數據項使用不同的Item來展示。如果有這樣一個需求:Model的數據項中有一個字段爲itemType,展示數據時希望能夠根據這個字段使用不同的Item來展示數據,能否實現呢?自然是可以的:我們可以將View的delegate字段設爲一個Loader,然後讓這個Loader根據itemType設置source,即可實現這個需求。
爲了簡單起見,展示數據的多個Item只是顏色不同,itemType可選的值有"red"/“green”/“blue”,那麼代碼如下:

// main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQml.Models 2.1

Window {
    visible: true
    width: 600
    height: 480
    title: qsTr("Hello World")

    ListModel {
        id: pageModel
        ListElement {
            itemType: "red"
            display: "red page"
        }
        ListElement {
            itemType: "green"
            display: "green page"
        }
        ListElement {
            itemType: "blue"
            display: "blue page"
        }
    }

    ListView {
        anchors.fill: parent
        orientation: ListView.Horizontal
        snapMode: ListView.SnapOneItem
        model: pageModel
        delegate: Loader {
            source: {
                switch (itemType) {
                case "red": return "RedPage.qml";
                case "green": return "GreenPage.qml";
                case "blue": return "BluePage.qml";
                }
            }
        }
    }
}

// RedPage.qml
import QtQuick 2.0

Rectangle {
    width: 200
    height: 480
    color: "red"
    Text {
        id: centerText
        anchors.centerIn: parent
        color: "white"
        text: display
    }
}

// GreenPage.qml
import QtQuick 2.0

Rectangle {
    width: 200
    height: 480
    color: "green"
    Text {
        id: centerText
        anchors.centerIn: parent
        color: "white"
        text: display
    }
}

// BluePage.qml
import QtQuick 2.0

Rectangle {
    width: 200
    height: 480
    color: "blue"
    Text {
        id: centerText
        anchors.centerIn: parent
        color: "white"
        text: display
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章