Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

GridView with model and additional items



  • Hi,

    I have a GridView where I add buttons coming from a model. However, I would like to add an additional item to the GridView which has a different type. Is it possible to add this additional item without modifying my model to account for both types?



  • @maxwell31 Hi! I'm guessing you're talking about having different delegate components to the GridView based on some conditions. If yes, can you relate the following code.

        Component {
            id: rectCompo
    
            Rectangle {
                width: 40
                height: width
                color: "red"
            }
        }
    
        Component {
            id: roundCompo
    
            Rectangle {
                width: 80
                height: width
                color: "green"
                radius: width /2
            }
        }
    
        GridView {
            model: 10
            width: 400
            height: width
    
            delegate: Loader {
                sourceComponent: index % 2 ? rectCompo : roundCompo
            }
        }
    


  • Ideally, I would like to keep some elements outside of the mode, e.g. have a model and then add some additional items, e.g. buttons



  • Hi @maxwell31 , i guess you need a different component depending upon some condition after the click,below is a sample code needed to achieve your functionality:-

    Button {
        text: "Update"
        anchors.top: gridView.bottom
        anchors.topMargin: 10
    
        onClicked: {
            gridModel.append( {"redRectVisible": false});
        }
    }
    
    ListModel {
        id: gridModel
    
        ListElement{
            redRectVisible: true
        }
    
        ListElement{
            redRectVisible: true
        }
    }
    
    GridView {
        id: gridView
    
        height: 200
        width: 200
        model: gridModel
        cellWidth: 100
        cellHeight: 100
    
        delegate: Item {
            height: gridView.cellHeight
            width: gridView.cellWidth
            Rectangle {
                height: parent.height
                width: parent.width
                color: "red"
                border.color: "black"
                visible: redRectVisible
            }
    
            Rectangle {
                height: parent.height
                width: parent.width
                color: "green"
                border.color: "black"
                visible: !redRectVisible
            }
        }
    }

Log in to reply